实现步骤:
服务端:
1. 添加feign的依赖
<!--openfeign (feign调用依赖)-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2. 启动类添加feign的注解
@EnableFeignClients
客户端:
1. 添加feign的依赖
<!--openfeign (feign调用依赖)-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2. 编写feign接口
package com.hnu.bigscreen;
import com.hnu.common.respone.PojoBaseResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
// name 为服务名,接口的路径名为restcontrol的路径+接口的路径
@FeignClient(name = "bigScrren")
public interface CarConditionFeign {
/**
* 根据carId获取该车最新车况信息
* @param id
* @return
*/
@RequestMapping("condition/getOneConditionByCarId/{id}")
public PojoBaseResponse getOneConditionByCarId(@PathVariable("id") String id);
/**
* kafka发送数据
* @return
*/
@PostMapping("condition/sendKafkaMessage")
public PojoBaseResponse sendKafkaMessage();
}
feign客户端配置
1. feiclient文件添加config注释,如下
@FeignClient(url = "${cmp.url}", name = "cmpService", configuration = FeignClientConfig.class)
public interface aaa {
}
2. 编写feignclient配置文件类
public class FeignClientConfig {
/**
* 超时时间
*/
@Value("${client.retryer.period}")
private Long period;
/**
* 重试间隔时间
*/
@Value("${client.retryer.maxPeriod}")
private Long maxPeriod;
/**
* 需要重试的次数 + 第一次请求的次数1
*/
@Value("${client.retryer.maxAttempts}")
private int maxAttempts;
@Bean
public Retryer feignRetryer() {
return new Retryer.Default(period, maxPeriod, maxAttempts);
}
}
整合断路器:
1. 整合hystric断路器
@FeignClient(url = "${vms.address}", name = "vmsService", configuration = FeignClientConfig.class, fallbackFactory = VmsClientFallback.class)
//TODO 添加fallback
public interface VmsClient {
}
2. 编写Fallback.class文件
@Component
public class VmsClientFallback implements FallbackFactory<VmsClient> {
@Autowired
private BdsSdRecordErrorLogService errorLogService;
@Override
public VmsClient create(Throwable throwable) {
return new VmsClient() {
@Override
public VmsResponse<VmsVehicleModelMetaData> getVehicleModelData(Object params) {
return new VmsResponse<>("001", throwable.getMessage());
}
@Override
public VmsResponse<VmsVehicleInspection> getVehicleInspectionData(Object params) {
return null;
}
@Override
public VmsResponse<VmsVehicleOffLine> getVehicleOffLineData(Object params) {
return null;
}
@Override
public VmsResponse<VmsVehicleSaleInfo> getVehicleSaleInfoData(Object params) {
return null;
}
@Override
public VmsResponse<VmsDealerInfo> getVehicleDealerData(Object params) {
return null;
}
};
}
}