什么是feign?
Feign是Netflix开发的声明式、模板化的HTTP客户端,其灵感来自Retrofit、JAXRS-2.0以及WebSocket。Feign可帮助我们更加便捷、优雅地调用HTTP API。
为什么要使用feign?
原先调用API会产生很多硬编码,在业务繁杂时显得非常冗余。所以,我们可以用更优雅的Feign来实现这个功能。
如何使用?
首先添加maven配置
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
该类与service层不在同一个包下面,相当于暴露给客户端调用的接口类, 添加@FeignClient注解指定服务名来绑定服务,url为服务端ip,configuration为请求配置。
使用feign注解@RequestLine,相当于去调用改请求,服务端需要使用Spring MVC的来实现该REST接口
也可以直接使用@RequestMapping并实现,既当客户端也当服务端
@FeignClient(name = "xm-provider-demo",url = "...请求路径", configuration = FeignConfig.class)
public interface FeignClient {
//@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
@RequestLine("GET /doSomething")
public void doSomething();
}
configuration类,
feign.Contract.Default() 相当于默认使用 @RequestLine,使用@RequestMapping不需要该contract
BasicAuthRequestInterceptor可在请求头添加信息,在服务端进行安全校验
@EnableFeignClients
@SpringBootConfiguration
public class FeignConfig {
@Bean
public Contract contract(){
return new feign.Contract.Default();
}
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor(username, password);
}
}
启动类添加@EnableFeignClients注解
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerMovieApplication.class, args);
}
}
还可以通过继承RequestInterceptor类,实现apply方法,可以在调用之前进行操作
public interface RequestInterceptor {
/**
* Called for every request. Add data using methods on the supplied {@link RequestTemplate}.
*/
void apply(RequestTemplate template);
}
关键的一步,应用需要依赖刚才的包,调用接口就等同于往服务器调用http请求
@Autowired
private FeignClient feignClient;
@PostMapping("/doSomething")
public void doSomething() {
feignClient.doSomething();
}