1、Feign
是一个声明式、模版化的HTTP客户端,有助于更便捷、优雅地调用HTTP API。在Spring Cloud中自动的为Feign整合了Ribbon和Eureka,使用时创建一个接口并添加@FeignClient即可
2、使用Demo
1)添加Feign依赖
<!-- Feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
2)创建Feign接口
import com.springcloud.demo.movie.User;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* user服务HTTP客户端
*/
@FeignClient(name = "user")
public interface UserFeignClient {
/**
* 请求/{id}接口
* @param id 路径参数
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
User findById(@PathVariable("id") Long id);
}
注:通过配置@FeignClient的url属性可指定请求的URL,configuration属性可自定义Feign的配置
3)启动类添加支持
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient // 声明这是一个EurekaClient,@EnableDiscoverClient是一个抽象声明,组件实现可以使用eureka、zookeeper、consul
@EnableFeignClients
public class MovieApplication {
public static void main(String[] args) {
SpringApplication.run(MovieApplication.class, args);
}
}
4)使用Feign调用
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return userFeignClient.findById(id);
}
3、自定义Feign配置
1)默认配置类FeignClientsConfiguration
a、默认已配置:Decoder、Encoder、Logger、Contract、Feign.Builder、Client
b、未给出默认配置项:Logger.Level、Retryer、ErrorDecoder、Request.Options、Collection
注:Feign 在默认情况下使用的是 JDK 原生的 URLConnection 发送HTTP请求,没有连接池,但是对每个地址会保持一个长连接,即利用 HTTP 的 persistence connection。支持使用ApacheHttpClient或者OkHttpCleint进行替换(Cleint)
2)自定义配置步骤
a、创建配置类
b、使用configuration属性指定使用的配置类
注:SpringCloud很多自定义配置基本上都是这个玩法,而且为了不被全局应用,自定义的配置类不应该被spring扫描到
4、Feign定义的接口还可以继承其他接口
不建议在服务端和客户端之间共享接口,一方面会紧耦合,另一方面Feign本身不使用SpringMVC的工作机制(方法参数的映射不会被继承)
5、Feign压缩
通过配置feign.compression.request.*和feign.compression.response.*来设置
6、Feign日志
每个Feign客户端都会创建一个logger,只对Debug级别响应,Logger.Level有四个实例
1)NONE:默认,不记录日志
2)BASIC:仅记录请求方法、URL、响应状态码、执行时间
3)HEADERS:BASIC基础上,记录请求和响应的header
4)FULL:header、body、元数据
7、多参数的使用方法
1)使用@RequestParam注解方法中的各个参数
2)使用@RequestParam Map<String, Object> map
3)使用@RequestBody T t