Feign的作用
Feign是Netflix公司开发的声明式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,代码会显得非常凌乱、不优雅、不易维护。
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@LoadBalancedpublic RestTemplate restTemplate(){return new RestTemplate();}
}
RestTemplate就可有可无了,无需理会。
编写FeignClient接口
创建一个接口文件UserService
@FeignClient(name="userservice",path="/user")
public interface IUserService {@GetMapping("/getUser")public User getUser();
}
通过@FeignClient注解,指定当前接口是一个FeignClient的接口文件,其中name属性指定其对应的微服务名称,path指定对该服务的访问路径。
接口方法支持SpringMVC的注解,比如@GetMapping、@PostMapping等等,相当于是在访问当前服务下的Controller方法一样。这为程序员在微服务环境下的服务调用提供了极大的方便,使得微服务调用变的轻而易举。
尤其,这个接口是不需要我们去实现的,由Feign在Spring Cloud服务启动过程中通过代理实现并自动注入到Spring Ioc容器中。所以我们在应用中可以直接通过自动装配引用。
回想一下MyBatis,和Mapper接口是否很类似?
对接口方法的调用
找到我们以前通过RestTemplate调用userservice服务的应用,通过@AutoWired注解自动装配IUserService ,直接调用接口方法getUser():
@Service
@Slf4j
public class OrderService {@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate 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 {@AutowiredOrderService orderService;@AutowiredFallbackHandle 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