Feign简介
在Spring Cloud中,使用Feign非常简单——创建一个接口,并在接口上添加一些注解,代码就完成了,Feign支持多种注解,Feign自带的或者JAX-RX注解等。
Spring Cloud对Feign进行了增强,使Feign支持了Spring MVC注解,并整合了Ribbon和Eureka,从而让Feign的使用更加方便
- 为服务消费者添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>1.4.4.RELEASE</version>
</dependency>
- 添加Feign接口,并添加@FeignClient注解
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name = "springbootprovider")
public interface HomeFeign {
@RequestMapping(value = "/home",method = RequestMethod.GET)
public String Home();
}
其中name = "springbootprovider"为指定服务提供者的名称,**@RequestMapping(value = “/home”,method = RequestMethod.GET)**这里的value不能为空,而且应该在服务提供端可以找到/home地址的接口。不然会报错
- 修改Controller,让其调用Feign接口
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import server.feign.HomeFeign;
@RestController
public class HomeComtroller {
@Autowired
private HomeFeign homeFeign;
@GetMapping("/home")
public String getHome(){
return this.homeFeign.Home();
}
}
- 修改启动类
@SpringBootApplication
@EnableFeignClients
public class DubboClient {
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args){
SpringApplication.run(DubboClient.class);
}
}
Feign的注释:
Comtroller的GetMapper主要是针对,用户浏览器的URL
Feign的接口的RequestMapping主要是针对提供方的路径。
自定义Feign配置
使用java代码自定义Feign配置
在SpringCloud中,feign的默认配置类是FeignClientsConfiguration自定义配置的优先级比FeignClientsConfiguration高
创建一个FeignConfiguration类:
public class feignContract(){
@Bean
public Contract feignContract(){
return new feign.Contract.Default();
}
}
注意:该类不写Configuration注解
然后将此配置类用上
@FeignClient(configuration=FeignConfuguration.class)
如果要配置的是全局配置那么,在启动类配置
@EnableFeignClients(defaultConfiguration = DefaultRibbonConfig.class)
通过属性自定义Feign配置
感觉此方法最方便