Feign 是 Spring Cloud Netflix 組件中的一個輕量級 RESTful 的 HTTP 服務客戶端,實現了負載均衡和 Rest 調用的開源框架,封裝了 Ribbon 和 RestTemplate,實現了 WebService 的面向接口編程,進一步下降了項目的耦合度。java
Feign 內置了 Ribbon,用來作客戶端負載均衡調用服務註冊中心的服務。git
Feign 自己並不支持 Spring MVC 的註解,它有一套本身的註解,爲了更方便的使用,Spring Cloud 孵化了 OpenFeign。github
Feign 是一種聲明式、模板化的 HTTP 客戶端(僅在 Consumer 中使用)。web
Feign 支持的註解和用法請參考官方文檔:https://github.com/OpenFeign/... 或 spring.io 官網文檔spring
Feign 的使用方式是:使用 Feign 的註解定義接口,調用這個接口,就能夠調用服務註冊中心的服務。apache
Feign 旨在使編寫 JAVA HTTP 客戶端變得更加容易,Feign 簡化了 RestTemplate 代碼,實現了 Ribbon 負載均衡,使代碼變得更加簡潔,也少了客戶端調用的代碼,使用 Feign 實現負載均衡是首選方案。只須要你建立一個接口,而後在上面添加註解便可。編程
Feign 是聲明式服務調用組件,其核心就是:像調用本地方法同樣調用遠程方法,無感知遠程 HTTP 請求。性能優化
OpenFeign 是 Spring Cloud 在 Feign 的基礎上支持了 Spring MVC 的註解,如 @RequesMapping
、@Pathvariable
等等。服務器
OpenFeign 的 @FeignClient
能夠解析 SpringMVC 的 @RequestMapping
註解下的接口,並經過動態代理的方式產生實現類,實現類中作負載均衡並調用服務。app
點擊連接觀看:Feign 入門案例視頻(獲取更多請關注公衆號「哈嘍沃德先生」)
feign-demo
聚合工程。SpringBoot 2.2.4.RELEASE
、Spring Cloud Hoxton.SR1
。
Feign 的使用主要分爲如下幾個步驟:
@FeignClient
註解聲明須要調用的服務;@EnableFeignClients
註解激活 Feign 組件。
PS:服務消費者經過 Eureka 註冊中心獲取服務,或者 Ribbon 點對點直連模式均可以使用 Feign 來實現。
咱們建立聚合項目並使用 Eureka 註冊中心來說解 Feign,首先建立一個 pom 父工程。
pom.xml
<?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> <groupId>com.example</groupId> <artifactId>feign-demo</artifactId> <version>1.0-SNAPSHOT</version> <!-- 繼承 spring-boot-starter-parent 依賴 --> <!-- 使用繼承方式,實現複用,符合繼承的均可以被使用 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.4.RELEASE</version> </parent> <!-- 集中定義依賴組件版本號,但不引入, 在子工程中用到聲明的依賴時,能夠不加依賴的版本號, 這樣能夠統一管理工程中用到的依賴版本 --> <properties> <!-- Spring Cloud Hoxton.SR1 依賴 --> <spring-cloud.version>Hoxton.SR1</spring-cloud.version> </properties> <!-- 項目依賴管理 父項目只是聲明依賴,子項目須要寫明須要的依賴(能夠省略版本信息) --> <dependencyManagement> <dependencies> <!-- spring cloud 依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> </project>
註冊中心咱們採用集羣方式構建,本文中使用兩個節點分別是 eureka-server
和 eureka-server02
。
eureka-server 和 eureka-server02 的建立過程一致。
eureka-server 和 eureka-server02 的依賴配置一致。
pom.xml
<?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> <groupId>com.example</groupId> <artifactId>eureka-server</artifactId> <version>1.0-SNAPSHOT</version> <!-- 繼承父依賴 --> <parent> <groupId>com.example</groupId> <artifactId>feign-demo</artifactId> <version>1.0-SNAPSHOT</version> </parent> <!-- 項目依賴 --> <dependencies> <!-- netflix eureka server 依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <!-- spring boot web 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- spring boot test 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </project>
eureka-server 的 application.yml
server: port: 8761 # 端口 spring: application: name: eureka-server # 應用名稱(集羣下相同) # 配置 Eureka Server 註冊中心 eureka: instance: hostname: eureka01 # 主機名,不配置的時候將根據操做系統的主機名來獲取 prefer-ip-address: true # 是否使用 ip 地址註冊 instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port client: # 設置服務註冊中心地址,指向另外一個註冊中心 service-url: # 註冊中心對外暴露的註冊地址 defaultZone: http://localhost:8762/eureka/
eureka-server02 的 application.yml
spring: application: name: eureka-server # 應用名稱(集羣下相同) # 端口 server: port: 8762 # 配置 Eureka Server 註冊中心 eureka: instance: hostname: eureka02 # 主機名,不配置的時候將根據操做系統的主機名來獲取 prefer-ip-address: true # 是否使用 ip 地址註冊 instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port client: # 設置服務註冊中心地址,指向另外一個註冊中心 service-url: # 註冊中心對外暴露的註冊地址 defaultZone: http://localhost:8761/eureka/
eureka-server 和 eureka-server02 的啓動類一致。
EurekaServerApplication.java
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication // 開啓 EurekaServer 註解 @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
服務提供者咱們採用集羣方式構建,本文中使用兩個節點分別是 service-provider
和 service-provider02
。
service-provider 和 service-provider02 的建立過程一致。
service-provider 和 service-provider02 的依賴配置一致。
pom.xml
<?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> <groupId>com.example</groupId> <artifactId>service-provider</artifactId> <version>1.0-SNAPSHOT</version> <!-- 繼承父依賴 --> <parent> <groupId>com.example</groupId> <artifactId>feign-demo</artifactId> <version>1.0-SNAPSHOT</version> </parent> <!-- 項目依賴 --> <dependencies> <!-- netflix eureka client 依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- spring boot web 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- lombok 依賴 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <!-- spring boot test 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </project>
service-provider 的 application.yml
server: port: 7070 # 端口 spring: application: name: service-provider # 應用名稱(集羣下相同) # 配置 Eureka Server 註冊中心 eureka: instance: prefer-ip-address: true # 是否使用 ip 地址註冊 instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port client: service-url: # 設置服務註冊中心地址 defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
service-provider02 的 application.yml
spring: application: name: service-provider # 應用名稱(集羣下相同) # 端口 server: port: 7071 # 配置 Eureka Server 註冊中心 eureka: instance: prefer-ip-address: true # 是否使用 ip 地址註冊 instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port client: service-url: # 設置服務註冊中心地址 defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
service-provider 和 service-provider02 的實體類一致。
Product.java
package com.example.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor public class Product implements Serializable { private Integer id; private String productName; private Integer productNum; private Double productPrice; }
service-provider 和 service-provider02 的服務代碼一致。
ProductService.java
package com.example.service; import com.example.pojo.Product; import java.util.List; /** * 商品服務 */ public interface ProductService { /** * 查詢商品列表 * * @return */ List<Product> selectProductList(); }
ProductServiceImpl.java
package com.example.service.impl; import com.example.pojo.Product; import com.example.service.ProductService; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; /** * 商品服務 */ @Service public class ProductServiceImpl implements ProductService { /** * 查詢商品列表 * * @return */ @Override public List<Product> selectProductList() { return Arrays.asList( new Product(1, "華爲手機", 1, 5800D), new Product(2, "聯想筆記本", 1, 6888D), new Product(3, "小米平板", 5, 2020D) ); } }
service-provider 和 service-provider02 的控制層一致。
ProductController.java
package com.example.controller; import com.example.pojo.Product; import com.example.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/product") public class ProductController { @Autowired private ProductService productService; /** * 查詢商品列表 * * @return */ @GetMapping("/list") public List<Product> selectProductList() { return productService.selectProductList(); } }
service-provider 和 service-provider02 的啓動類一致。
ServiceProviderApplication.java
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // 開啓 EurekaClient 註解,目前版本若是配置了 Eureka 註冊中心,默認會開啓該註解 //@EnableEurekaClient public class ServiceProviderApplication { public static void main(String[] args) { SpringApplication.run(ServiceProviderApplication.class, args); } }
在剛纔的父工程下建立一個 service-consumer
服務消費者的項目。
服務消費者添加 openfeign
依賴。
pom.xml
<?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> <groupId>com.example</groupId> <artifactId>service-consumer</artifactId> <version>1.0-SNAPSHOT</version> <!-- 繼承父依賴 --> <parent> <groupId>com.example</groupId> <artifactId>feign-demo</artifactId> <version>1.0-SNAPSHOT</version> </parent> <!-- 項目依賴 --> <dependencies> <!-- netflix eureka client 依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- spring cloud openfeign 依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- spring boot web 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- lombok 依賴 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <!-- spring boot test 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </project>
application.yml
server: port: 9090 # 端口 spring: application: name: service-consumer # 應用名稱 # 配置 Eureka Server 註冊中心 eureka: client: register-with-eureka: false # 是否將本身註冊到註冊中心,默認爲 true registry-fetch-interval-seconds: 10 # 表示 Eureka Client 間隔多久去服務器拉取註冊信息,默認爲 30 秒 service-url: # 設置服務註冊中心地址 defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
Product.java
package com.example.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor public class Product implements Serializable { private Integer id; private String productName; private Integer productNum; private Double productPrice; }
Order.java
package com.example.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor public class Order implements Serializable { private Integer id; private String orderNo; private String orderAddress; private Double totalPrice; private List<Product> productList; }
ProductService.java
package com.example.service; import com.example.pojo.Product; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; // 聲明須要調用的服務 @FeignClient("service-provider") public interface ProductService { /** * 查詢商品列表 * * @return */ // 配置須要調用的服務地址及參數 @GetMapping("/product/list") List<Product> selectProductList(); }
OrderService.java
package com.example.service; import com.example.pojo.Order; public interface OrderService { /** * 根據主鍵查詢訂單 * * @param id * @return */ Order selectOrderById(Integer id); }
OrderServiceImpl.java
package com.example.service.impl; import com.example.pojo.Order; import com.example.service.OrderService; import com.example.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class OrderServiceImpl implements OrderService { @Autowired private ProductService productService; /** * 根據主鍵查詢訂單 * * @param id * @return */ @Override public Order selectOrderById(Integer id) { return new Order(id, "order-001", "中國", 22788D, productService.selectProductList()); } }
OrderController.java
package com.example.controller; import com.example.pojo.Order; import com.example.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/order") public class OrderController { @Autowired private OrderService orderService; /** * 根據主鍵查詢訂單 * * @param id * @return */ @GetMapping("/{id}") public Order selectOrderById(@PathVariable("id") Integer id) { return orderService.selectOrderById(id); } }
ServiceConsumerApplication.java
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication // 開啓 EurekaClient 註解,目前版本若是配置了 Eureka 註冊中心,默認會開啓該註解 //@EnableEurekaClient // 開啓 FeignClients 註解 @EnableFeignClients public class ServiceConsumerApplication { public static void main(String[] args) { SpringApplication.run(ServiceConsumerApplication.class, args); } }
當前環境運行結果以下:
訪問:http://localhost:9090/order/1
Feign 封裝了 Ribbon 天然也就集成了負載均衡的功能,默認採用輪詢策略。如何修改負載均衡策略呢?與以前學習 Ribbon 時講解的配置是一致的。
在啓動類或配置類中注入負載均衡策略對象。全部服務請求均使用該策略。
@Bean public RandomRule randomRule() { return new RandomRule(); }
修改配置文件指定服務的負載均衡策略。格式:服務應用名.ribbon.NFLoadBalancerRuleClassName
# 負載均衡策略 # service-provider 爲調用的服務的名稱 service-provider: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
使用 @PathVariable
註解或 @RequestParam
註解接收請求參數。
ProductService.java
/** * 根據主鍵查詢商品 * * @param id * @return */ Product selectProductById(Integer id);
ProductServiceImpl.java
/** * 根據主鍵查詢商品 * * @param id * @return */ @Override public Product selectProductById(Integer id) { return new Product(id, "冰箱", 1, 2666D); }
ProductController.java
package com.example.controller; import com.example.pojo.Product; import com.example.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/product") public class ProductController { @Autowired private ProductService productService; /** * 根據主鍵查詢商品 * * @param id * @return */ @GetMapping("/{id}") public Product selectProductById(@PathVariable("id") Integer id) { return productService.selectProductById(id); } }
ProductService.java
package com.example.service; import com.example.pojo.Product; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; // 聲明須要調用的服務 @FeignClient("service-provider") public interface ProductService { /** * 根據主鍵查詢商品 * * @return */ @GetMapping("/product/{id}") Product selectProductById(@PathVariable("id") Integer id); }
OrderServiceImpl.java
package com.example.service.impl; import com.example.pojo.Order; import com.example.service.OrderService; import com.example.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Arrays; @Service public class OrderServiceImpl implements OrderService { @Autowired private ProductService productService; /** * 根據主鍵查詢訂單 * * @param id * @return */ @Override public Order selectOrderById(Integer id) { return new Order(id, "order-003", "中國", 2666D, Arrays.asList(productService.selectProductById(5))); } }
訪問:http://localhost:9090/order/3 結果以下:
使用 @RequestBody
註解接收請求參數。
ProductService.java
/** * 根據主鍵查詢商品 * * @param id * @return */ Product queryProductById(Integer id); /** * 新增商品 * * @param product * @return */ Map<Object, Object> createProduct(Product product);
ProductServiceImpl.java
/** * 根據主鍵查詢商品 * * @param id * @return */ @Override public Product queryProductById(Integer id) { return new Product(id, "冰箱", 1, 2666D); } /** * 新增商品 * * @param product * @return */ @Override public Map<Object, Object> createProduct(Product product) { System.out.println(product); return new HashMap<Object, Object>() {{ put("code", 200); put("message", "新增成功"); }}; }
ProductController.java
package com.example.controller; import com.example.pojo.Product; import com.example.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; @RestController @RequestMapping("/product") public class ProductController { @Autowired private ProductService productService; /** * 根據主鍵查詢商品 * * @param id * @return */ @PostMapping("/single") public Product queryProductById(@RequestBody Integer id) { return productService.queryProductById(id); } /** * 新增商品 * * @param product * @return */ @PostMapping("/save") public Map<Object, Object> createProduct(@RequestBody Product product) { return productService.createProduct(product); } }
ProductService.java
package com.example.service; import com.example.pojo.Product; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.util.List; import java.util.Map; // 聲明須要調用的服務 @FeignClient("service-provider") public interface ProductService { /** * 根據主鍵查詢商品 * * @param id * @return */ @PostMapping("/product/single") Product queryProductById(Integer id); /** * 新增商品 * * @param user * @return */ @PostMapping("/product/save") Map<Object, Object> createProduct(Product user); }
爲了方便測試,直接建立入口調用,不經過訂單服務去調用商品服務了。
ProductController.java
package com.example.controller; import com.example.pojo.Product; import com.example.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController @RequestMapping("/product") public class ProductController { @Autowired private ProductService productService; /** * 根據主鍵查詢商品 * * @param id * @return */ @PostMapping("/info") public Product queryProductById(Integer id) { return productService.queryProductById(id); } /** * 新增商品 * * @param product * @return */ @PostMapping("/save") public Map<Object, Object> createProduct(Product product) { return productService.createProduct(product); } }
訪問:http://localhost:9090/product/info 請求參數爲 id=5
結果以下:
訪問:http://localhost:9090/product/save 請求參數爲 id=6&productName=耳機&productNum=1&productPrice=288
結果以下:
下一篇咱們講解 Feign 性能優化的問題,Gzip壓縮、HTTP鏈接池、請求超時等,記得關注噢~
本文采用 知識共享「署名-非商業性使用-禁止演繹 4.0 國際」許可協議
。
你們能夠經過 分類
查看更多關於 Spring Cloud
的文章。
🤗 您的點贊
和轉發
是對我最大的支持。
📢 掃碼關注 哈嘍沃德先生
「文檔 + 視頻」每篇文章都配有專門視頻講解,學習更輕鬆噢 ~