作用:简单的说就是,在微服务中,用于跨服务的调用。
用法
1.引入pom
2.在启动类增加注解
@EnableFeignClients(basePackages = {"com.fcs"})
//basePackages属性是配置扫描哪些包下
3.写feign的调用接口
使用注解:
@FeignClient
举例:
@FeignClient(contextId = "coudAccountService", value = "hcloud-cpc", configuration = FeignConfiguration.class, fallbackFactory = CpcCloudAccountServiceFallBackFactory.class)
public interface CpcCloudAccountService {
@PostMapping("/cloudAccount")
R<CpcCloudAccount> create(@RequestBody CpcCloudAccount cpcCloudAccount);
@RequestMapping(method = RequestMethod.GET, value = "/cloudAccount/{id}")
R<CpcCloudAccount> findById(@RequestParam String id);
@RequestMapping(method = RequestMethod.GET, value = "/cloudAccount")
R<List<CpcCloudAccount>> getAll(@RequestParam String cloudType);
@GetMapping("/cloudAccount/findByAccount")
R<CpcCloudAccount> findByAccount(@RequestParam(required = false) String account);
@GetMapping("/cloudAccount/audit")
R<CpcCloudAccount> audit(@RequestParam String account, @RequestParam Integer status);
}
属性介绍:
value:
就是微服务暴露的服务名称
contextId:
比如我们有个user服务,但user服务中有很多个接口,我们不想将所有的调用接口都定义在一个类中,比如:
Client 1
@FeignClient(name = "optimization-user")
public interface UserRemoteClient {
@GetMapping("/user/get")
public User getUser(@RequestParam("id") int id);
}
Client 2
@FeignClient(name = "optimization-user")
public interface UserRemoteClient2 {
@GetMapping("/user2/get")
public User getUser(@RequestParam("id") int id);
}
这种情况下启动就会报错了,因为Bean的名称冲突了,具体错误如下:
Description:
The bean 'optimization-user.FeignClientSpecification', defined in null, could not be registered. A bean with that name has already been defined in null and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
解决方案就是为每个Client手动指定不同的contextId,这样就不会冲突了。
configuration:
用于指定配置类
fallbackFactory:
是容错的处理,可以知道熔断的异常信息。指定的类必须实现BaseFallbackFactory接口
举例:
@Component
public class CpcCloudAccountServiceFallBackFactory implements BaseFallbackFactory<CpcCloudAccountService> {
@Override
public CpcCloudAccountService create(Throwable throwable) {
return new CpcCloudAccountService() {
@Override
public R<CpcCloudAccount> create(@RequestBody CpcCloudAccount cpcCloudAccount){
return bizHandle(throwable);
}
@Override
public R<CpcCloudAccount> findById(@RequestParam String id){
return bizHandle(throwable);
}
};
}
}
从feign接口点实现会直接链接到这里
openFeign超时设置
openFeign默认等待一秒钟,没有返回就会报错,底层实际是ribbon
调用超时的时间可以在yml中配置
ribbon:
#指的是建立连接所用的时间,适用于网络状态正常的情况下,两端连接所用的时间
ReadTimeout: 5000
#指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
日志检测
1.写配置类
@Configuration
public class AsyncConfiguration {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
2.FeignClient注解中指定该配置类
@FeignClient(configuration = AsyncConfiguration .class)
3.配置yml
logging:
level:
# feign日志以什么级别监听哪个接口
com.fcs.omp.feign.cpc.service.CpcCloudAccountService: debug