feign的主要作用是结合了restTemplate和ribbon,发起远程调用和负载均衡。
想要使用feign先要引入feign的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在启动类上加入@EnableFeignClients,如果编写了配置类后面可以跟上配置类
消费者可以新建一个类,类上加入@FeignClients("服务名")
@GetMapping("/路径名")
返回值类型 方法名 (@PathVariable("参数名") 参数类型 参数名)
例如
@FeignClient("userservice")
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
当然这只是简单地使用feign
一般在企业中会单独建立一个feign-api的model
引入openfeign依赖
编写feign的配置和实体类
在需要用到feign的消费者中引入feign-api的依赖
引入相关的类
最重要的是 ,之前直接使用,相应的@FeignClients("服务名")是在消费者自己的包里的 可以直接找到
但如果放在了feign-api这个model中,消费者的启动类就不能直接找到@FeignClients
所以要在消费者的启动类上加入配置
@EnableFeignClients(clients = {类名.class} )
这样再启动就没问题了
关于feign的调优部分
feign底层默认是用的是URLConnection 是不支持连接池的
可以更改为OKHttp或者 Apache HTTPClient
引入依赖
<!--httpClient--> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-httpclient</artifactId> </dependency>
编写application.yaml
feign:
httpclient:
enabled: true #启动httpClient 默认也是开启的
max-connections: 200
max-connections-per-route: 50
这样就开启了httpClient
在一个调优就是feign的日志类别
feign有四个日志级别 none, basic, headers, FULL
一般调错的时候可以设置为FULL,但这太消耗性能了
默认情况下feign的日志级别为none,
也可以设置为basic
需要编写配置类
public class DefaultFeginConfiguration { @Bean public Logger.Level logLevel(){ return Logger.Level.BASIC; } }
然后再启动类上加入注解
@EnableFeignClients(defaultConfiguration = DefaultFeginConfiguration.class)