Spring cloud無縫集成Feign的使用示例詳解
Feign的作用
Feign是Netflix公司開發(fā)的聲明式web客戶端組件,Spring對Feign做了無縫集成:
Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Eureka, as well as Spring Cloud LoadBalancer to provide a load-balanced http client when using Feign.
可以通過Feign注解或JAX-RS注解使用,Feign也支持拔插式的編解碼。Spring Cloud增加了對Spring MVC注解的支持,并且在SpringMVC項目中默認使用HttpMessageConverters 轉換器。同時,Spring Cloud集成了Eureka、Spring Cloud LoadBalancer等組件,以提供在使用Feign組件時的負載均衡。
為什么要使用Feign
由于Spring6.0之后有了自己的Web客戶端組件,所以在Spring Cloud2022之后,Spring官方其實是在逐步的移除Feign、而使用自己的Web客戶端組件作為替代。
但是不管是誰,我們項目中都需要一個比RestTemplate更加靈活的Web客戶端組件。因為RestTemplate使用起來確實非常不方便:
public User getUserByRestTemplate(){ String url="http://userservice/user/getUser"; System.out.println("url"+url); // int c = 1/0; return restTemplate.getForObject(url,User.class); }
應用中會有很多地方需要調用微服務userservice的接口,每一個調用的地方都需要寫url,代碼會顯得非常凌亂、不優(yōu)雅、不易維護。
Feign可以完美解決以上RestTemplate的問題,尤其是Spring Cloud整合Eureka和Spring LoadBalancer之后,還可以輕松實現負載均衡。
Feign的使用
pom文件引入openfeign
我們以前面幾篇文章的案例為基礎,在Eureka、Spring LoadBalancer、Hystrix框架基礎上搭建Feign。
首先在orderservice模塊下,pom文件引入openFeign:
<?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"> <parent> <artifactId>springCloud</artifactId> <groupId>com.example</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>orderservice</artifactId> <properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.example</groupId> <artifactId>userService</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> <version>2.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies> </project>
orderService啟動類啟用FeignClients
在orderService的啟動類中通過@EnableFeignClients注解啟用FeignClient:
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableEurekaClient @EnableCircuitBreaker @EnableFeignClients public class OrderServiceApplication { public static void main(String[] args) { SpringApplication.run(OrderServiceApplication.class); } @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }
RestTemplate就可有可無了,無需理會。
編寫FeignClient接口
創(chuàng)建一個接口文件UserService
@FeignClient(name="userservice",path="/user") public interface IUserService { @GetMapping("/getUser") public User getUser(); }
通過@FeignClient注解,指定當前接口是一個FeignClient的接口文件,其中name屬性指定其對應的微服務名稱,path指定對該服務的訪問路徑。
接口方法支持SpringMVC的注解,比如@GetMapping、@PostMapping等等,相當于是在訪問當前服務下的Controller方法一樣。這為程序員在微服務環(huán)境下的服務調用提供了極大的方便,使得微服務調用變的輕而易舉。
尤其,這個接口是不需要我們去實現的,由Feign在Spring Cloud服務啟動過程中通過代理實現并自動注入到Spring Ioc容器中。所以我們在應用中可以直接通過自動裝配引用。
回想一下MyBatis,和Mapper接口是否很類似?
對接口方法的調用
找到我們以前通過RestTemplate調用userservice服務的應用,通過@AutoWired注解自動裝配IUserService ,直接調用接口方法getUser():
@Service @Slf4j public class OrderService { @Autowired private RestTemplate restTemplate; @Autowired private IUserService userService; public String getOrder(){ //通過userService獲取user信息 // User user = getUserByRestTemplate(); User user = getUserByFeign(); // System.out.println(user); return user.getName(); } public User getUserByRestTemplate(){ String url="http://userservice/user/getUser"; System.out.println("url"+url); // int c = 1/0; return restTemplate.getForObject(url,User.class); } public User getUserByFeign(){ return userService.getUser(); } }
測試
分別啟動Eureka模塊、orderservice模塊、userservice模塊:
瀏覽器訪問測試:
說明Feign已經正常工作。
反復刷新訪問:
說明Spring LoadBalancer已經正常工作。
在使用RestTemplate作為WEB客戶端的時候,我們需要通過@LoadBalanced注解來啟用Spring LoadBalancer負載均衡,但是FeignClient并不需要做什么,自動集成了負載均衡。
集成Hystrix
orderService服務的Controller中增加@HystrixCommand配置:
@RestController @RequestMapping("/order") @Slf4j public class OrderController { @Autowired OrderService orderService; @Autowired FallbackHandle fallbackHandle; @GetMapping("/getOrder") @HystrixCommand(fallbackMethod = "fallback",commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000") }) public String getOrder(){ log.info("Come here to get Order....123==="); return orderService.getOrder(); } public String fallback(){ return "orderService服務異常"; } }
然后userservice的getUser方法添加sleep使其超時:
@RestController @RequestMapping("/user") @Slf4j public class UserController { @Value("${server.port}") private String serverPort; @GetMapping("/getUser") @HystrixCommand(fallbackMethod = "fallback",commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "8000") }) public User getUser(){ log.info("userController's getuser comming......"); User user=new User(); user.setName("zhangsan from:"+serverPort); try{ log.info("I am sleepint for 10 second"); Thread.sleep(10*1000); log.info("I weekup"); }catch (Exception e){ } return user; } public User fallback(){ User user=new User(); user.setName("userService服務異常"); return user; } }
前端訪問驗證:
如果修改userService的@HystrixCommand超時時長參數為2秒,則:
說明Hystrix組件已經可以正常工作,與Feign組件進行了無縫集成。
Spring cloud feign官網:https://cloud.spring.io/spring-cloud-openfeign/reference/html...
以上就是Spring cloud無縫集成Feign的使用示例詳解的詳細內容,更多關于Spring cloud無縫集成Feign的資料請關注腳本之家其它相關文章!
相關文章
MyBatis-Plus updateById不更新null值的方法解決
用Mybatis-Plus的updateById()來更新數據時,無法將字段設置為null值,更新后數據還是原來的值,本文就來詳細的介紹一下解決方法,具有一定的參考價值,感興趣的可以了解一下2023-08-08使用Prometheus監(jiān)控Tomcat等java應用的狀態(tài)
本文介紹了如何配置Tomcat監(jiān)控,使用JMX Exporter和Prometheus進行監(jiān)控,并通過Grafana展示監(jiān)控數據2024-12-12mybatis-plus批量更新updateBatchById問題
這篇文章主要介紹了mybatis-plus批量更新updateBatchById問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07解析WeakHashMap與HashMap的區(qū)別詳解
本篇文章是對WeakHashMap與HashMap的區(qū)別進行了詳細的分析介紹,需要的朋友參考下2013-05-05