文章目录
一、OpenFeign介绍
1. 什么是OpenFeign?
OpenFeign是一个基于Java的声明式HTTP客户端框架,它简化了编写HTTP客户端的过程。提供了一种声明式的方式来定义和处理HTTP请求,使得开发者能够更加高效地构建和管理微服务。
2. 为什么要使用OpenFeign?
Ribbon需要手动配置大量的参数,包括服务实例列表、负载均衡策略、超时设置、重试机制等。这些参数须在请求的URL中进行拼接,如果参数少的话或许我们还可以忍受,一旦有多个参数的话,特别是在面对大规模的微服务架构时,需要耗费大量的时间和精力来进行配置。
二、OpenFeign实战
1. 创建工程
在springcloud-parent下创建工程 springcloud-pay-server:
springcloud-parent
springcloud-eureka-server
springcloud-order-server
springcloud-pay-server //支付服务用来集成Feign
springcloud-user-common
springcloud-user-server
2. 导入依赖
导入Feign,Eureka Client和web的依赖包,同时依赖user-common模块:
<dependencies>
<!--1.导入EurekaClient的包-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--2.导入Feign的包-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--web包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--user-common-->
<dependency>
<groupId>cn.itsource.springboot</groupId>
<artifactId>springcloud-user-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
3. 编写配置类
启动类配置:
//声明Eureka客户端
@EnableEurekaClient
//开启Feign的支持
@EnableFeignClients
@SpringBootApplication
public class PayApp {
public static void main(String[] args) {
SpringApplication.run(PayApp.class);
}
}
yml文件配置:
server:
port: 8764
eureka:
client:
serviceUrl:
defaultZone: http://peer1:8761/eureka/
instance:
instance-id: pay-server:8764 #实例ID
prefer-ip-address: true #使用ip注册到注册中心
spring:
application:
name: pay-server
4. 编写Feign的客户端接口
//Feign根据服务名能够在注册中心找到目标服务的通信地址
@FeignClient(value = "user-server")
public interface UserFeignClient {
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
User getById(@PathVariable("id")Long id);
}
5. 编写Controller使用Feign接口
通过注入UserFeignClient ,直接发起调用:
@RestController
public class PayController {
@Autowired
private UserFeignClient userFeignClient;
//浏览器来掉
@RequestMapping("/pay/{id}")
public User getById(@PathVariable("id")Long id){
//使用Feign调用用户服务获取User
return userFeignClient.getById(id);
}
}
6. 测试
通过浏览器访问pay-server的controller:http://localhost:8764/pay/1,多次请求发现依然默认使用了轮询策略。
7. Feign的工作原理
要使用Feign,我们除了导入依赖之外,需要主配置类通过@EnableFeignClients(value="")
注解开启Feign,也可以通过value属性指定了Feign的扫描包。同时我们需要为Feign编写客户端接口,接口上需要注解@FeignClient
标签。 当程序启动,注解了@FeignClient
的接口将会被扫描到然后交给Spring管理。
当请求发起,会使用jdk的动态代理方式代理接口,生成相应的RequestTemplate
,Feign会为每个方法生成一个RequestTemplate同时封装好http信息,如:url,请求参数等等
最终RequestTemplate生成request请求,交给Http客户端
(UrlConnection ,HttpClient,OkHttp)。然后Http客户端会交给LoadBalancerClient,使用Ribbon的负载均衡发起调用。