Feign
Feign是一个声明式服务调用工具,使用它,我们只要定义接口即可,Feign会帮我们动态生成一个实现了这个接口的类,这个类进行请求的封装,比直接用RestTemplate更简单。
基本使用:
1、新建项目的时候选择Feign或者在pom中新增(不同版本不一样,建议用Starter来建)
org.springframework.cloud
spring-cloud-starter-openfeign
2、在**Application上标注@EnableFeignClients、@EnableDiscoveryClient
3、针对服务器端这个/calc/add接口:编写接口
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("restservice1")
public interface CalcService {
@RequestMapping("/calc/add")
public int add(@RequestParam("i") int i,@RequestParam("j") int j);
}
不能在接口上声明@RequestMapping,在降级的时候好像会有坑
其中@FeignClient(“restservice1”)表示接口绑定restservice1这个服务。@RequestMapping("/calc/add")表示绑定服务器端哪个路径。@RequestParam(“j”)表示参数来自于请求参数中的名字。
4、在使用的地方注入CalcService即可。
如果获取报文头中的参数信息就用@RequestHeader,如果获取Json报文体,则使用@ReqeustBody。
Feign的服务降级
1、启用hystrix,在application.properties中添加
feign.hystrix.enabled=true
2、编写接口的实现类:
@Component
public class CalcServiceFallBack implements CalcService {
@Override
public int add(@RequestParam("i") int i,@RequestParam("j") int j) {
return -1;
}
}
然后修改CalcService接口的注解,变成:@FeignClient(name=“restservice1”,fallback=CalcServiceFallBack.class),也就是指定这个接口的降级类是CalcServiceFallBack