【OpenFeign】基礎使用
- 1. Feign介紹
- 1.1 使用示例
- 1.2 Feign與RPC對比
- 1.3 SpringCloud Alibaba快速整合OpenFeign
- 1.3.1 詳細代碼
1. Feign介紹
1.什么是 Feign
Feign 是 Netflix 開發的一個 聲明式的 HTTP 客戶端,在 Spring Cloud 中被廣泛使用。它的目標是:讓我們調用遠程 HTTP API 的方式,像調用本地接口一樣簡單。
換句話說:
- 不用手寫 RestTemplate 的各種請求
- 只要定義一個接口 + 注解,Spring Cloud Feign 就會幫你生成實現類,并通過 HTTP 調用對應的遠程服務。
2.Feign 的核心特點
-
聲明式調用:只需在接口上加注解 (@FeignClient),不用寫具體實現。
-
與 Spring Cloud 集成:能和 Eureka、Nacos 等注冊中心結合,實現服務發現。
-
內置負載均衡:在 Spring Cloud Netflix 時代默認結合 Ribbon,現在一般結合 Spring Cloud LoadBalancer。
-
支持攔截器:可以統一處理請求頭(如 token)、日志打印、重試等。
-
支持編碼解碼:內置 JSON 編解碼,可以和 Jackson、Gson 等整合。
3.Feign 的發展
Netflix Feign(早期版本):最初由 Netflix 開發,后被 Spring Cloud 整合。
OpenFeign(現在常用的版本):Spring Cloud 現在默認使用的是 Spring Cloud OpenFeign,它是對 Feign 的增強版本。
1.1 使用示例
假設有一個 user-service 提供 REST 接口:
@RestController
@RequestMapping("/user")
public class UserController {@GetMapping("/{id}")public User getUser(@PathVariable Long id) {return new User(id, "張三");}
}
在另一個服務(比如 order-service)中,我們要調用 user-service:
① 定義 Feign 接口
@FeignClient(name = "user-service") // user-service 是注冊在 Nacos/Eureka 上的服務名
public interface UserClient {@GetMapping("/user/{id}")User getUserById(@PathVariable("id") Long id);
}
② 注入并調用
@Service
public class OrderService {@Autowiredprivate UserClient userClient;public void createOrder(Long userId) {User user = userClient.getUserById(userId); // 直接像調用本地方法一樣System.out.println("下單用戶: " + user.getName());}
}
這樣,Feign 就會幫你把 getUserById() 變成 HTTP 調用。
1.2 Feign與RPC對比
特性 | Feign(HTTP 客戶端) | RPC(Dubbo/gRPC 等) |
---|---|---|
協議 | HTTP/HTTPS (REST) | TCP/HTTP2/自定義協議 |
序列化方式 | JSON / XML | Protobuf / Hessian / Thrift |
調用方式 | HTTP 請求,返回 JSON | 遠程方法調用(接近本地調用) |
性能 | 中等(HTTP+JSON 有開銷) | 高效(協議二進制、TCP直連) |
跨語言支持 | 很好(所有語言都支持 HTTP) | 較好(需官方 SDK,如 gRPC) |
常見場景 | Web 微服務調用 | 高性能微服務 / 內部系統調用 |
1.3 SpringCloud Alibaba快速整合OpenFeign
1.引入依賴
2.編寫調用接口+@FeignClient注解
3.調用端在啟動類上添加@EnableFeignClients注解
4.發起調用,像本地方法一樣調用
1.3.1 詳細代碼
調用方
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.beijing</groupId><artifactId>springcloudalibaba</artifactId><version>0.0.1-SNAPSHOT</version></parent><groupId>com.beijing</groupId><artifactId>order-openFeign</artifactId><version>1.0.1-SNAPSHOT</version><name>order</name><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!-- 添加openFeign --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency></dependencies></project>
server:port: 14031management:endpoints:web:exposure:include=*:spring:application:name: order-openFeigncloud:nacos:discovery:server-addr: 115.190.126.xxx:8848namespace: prodgroup: demo-1
package com.beijing.controller;import com.beijing.order.feign.StockFeignService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;/*** @author aaa* @version 1.0* @date 2025/08/27*/
@RestController
@RequestMapping("/order")
public class OrderController {@Resourceprivate StockFeignService stockFeignService;@RequestMapping("/add")public String add() {String reduct = stockFeignService.reduct();return "add order" + reduct;}
}
package com.beijing;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;/*** @author aaa* @version 1.0* @date 2025/08/27*/
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class OrderFeignApplication {public static void main(String[] args) {SpringApplication.run(OrderFeignApplication.class, args);}
}
package com.beijing.order.feign;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;@FeignClient(name = "stock", path = "/stock")
public interface StockFeignService {@RequestMapping("/reduct")public String reduct();
}
被調用方
package com.beijing;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;/*** @author aaa* @version 1.0* @date 2025/08/27*/
@EnableDiscoveryClient
@SpringBootApplication
public class StockApplication {public static void main(String[] args) {SpringApplication.run(StockApplication.class, args);}
}
package com.beijing.Controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author fanzhen@ict.ac.cn* @version 1.0* @date 2025/08/27*/
@RestController
@RequestMapping("/stock")
public class StockController {@RequestMapping("/reduct")public String reduct() {System.out.println("扣減庫存開始");return "扣減庫存成功";}
}
server:port: 14029management:endpoints:web:exposure:include=*:spring:application:name: stockcloud:nacos:discovery:server-addr: 115.190.126.xxx:8848namespace: prodgroup: demo-1
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.beijing</groupId><artifactId>springcloudalibaba</artifactId><version>0.0.1-SNAPSHOT</version></parent><groupId>com.beijing</groupId><artifactId>stock</artifactId><version>1.0.1-SNAPSHOT</version><name>stock</name><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency></dependencies></project>