微服务专题
前言
本系列带着大家深入微服务 Spring 体系的各个框架的底层原理。上一篇文章介绍了 SpringBoot 自动装配原理,本节将带着大家熟悉下 SpringCloud 体系的调用组件 Feign
Feign 是什么
Feign是一个声明式 Web 服务客户端。它使编写 Web 服务客户端更容易
它具有可插入的注解支持,包括 Feign 注解和 JAX-RS 注解
Feign 还支持可插拔的编码器和解码器
对 Spring MVC 注解的支持,并支持使用HttpMessageConvertersSpring Web 中默认使用的注解
Spring Cloud 集成了 Eureka、Spring Cloud CircuitBreaker 以及 Spring Cloud LoadBalancer,使用 Feign 时提供负载均衡的 http 客户端
SpringCloud 整合 Feign
加入 pom 依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
复制代码
启用 Feign 客户端
@SpringBootApplication@EnableFeignClientspublic class Application {
public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
复制代码
创建一个 Spring Cloud LoadBalancer client
@FeignClient("demo")public interface DemoFeignClient { @RequestMapping(method = RequestMethod.GET, value = "/getDemo") DemoDTO getDemo();}
复制代码
rpc 调用 client
@RestController@RequestMapping("/remote")public class RemoteService {
@Autowired DemoFeignClient demoFeignClient;
@RequestMapping(value = "/getRemoteDemo") public DemoDTO getRemoteDemo() { DemoDTO result = demoFeignClient.getDemo(); return result; }}
复制代码
Feign 核心配置
超时配置
相关配置解释:
connectTimeout :建立连接所用的超时时间
readTimeout :从连接建立时开始,并在返回响应的时间
1)针对 feign 配置
feign: client: config: feignName: connectTimeout: 5000 readTimeout: 5000
复制代码
2)通用配置
feign: client: config: default: connectTimeout: 5000 readTimeout: 5000
复制代码
拦截器配置
可以使用 feign 的拦截器功能实现接口的验证、鉴权功能
1)Basic 认证
@Configurationpublic class DemoFeignConfiguration { @Bean public BasicAuthRequestInterceptor basicAuthRequestInterceptor() { return new BasicAuthRequestInterceptor("user", "password"); }}
复制代码
2)自定义拦截器实现需要实现接口 RequestInterceptor
public interface RequestInterceptor {
/** * Called for every request. Add data using methods on the supplied {@link RequestTemplate}. */ void apply(RequestTemplate template);}
复制代码
2.1)请求头放上 TOKEN 认证信息
public class UserInfoRequestInterceptor implements RequestInterceptor {
public void apply(RequestTemplate template) { template.header("USER-INFO", "TOKEN"); }}
复制代码
2.2)将配置添加到 feign
feign: client: config: feignName: connectTimeout: 5000 readTimeout: 5000 requestInterceptors: - com.example.UserInfoRequestInterceptor
复制代码
日志配置
Feign 使用过程中需要打印日志可以实现 Fegin 的 Logger 功能,可以打印 http 的调用链路用于功能调试。
1)Logger.Level 级别:
2)配置 2.1) yaml 配置
logging: level: com.example.feign.DemoFeign: debug
复制代码
2.2) Config 配置
@Configurationpublic class FeignConfiguration { @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; }}
复制代码
@FeignClient 常用属性
评论