首先在项目中新建一个独立的模块xx-xx-api,里面封装的是feign接口,对外提供能力。
maven依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
接口:name指的的是服务的名称,path指的是服务的前缀,若服务包含前缀必须指明,否则404
@FeignClient(name = "terminal-device", path = "/terminal-device", fallbackFactory = DeviceFeignClientFallbackFactory.class)
public interface DeviceFeignClient {
@RequestMapping(value = "/v2/device/deviceInfo", method = RequestMethod.POST,consumes = "application/json")
SerializableResult<DeviceInfoOutVo> deviceInfo(@RequestBody DeviceOutDto deviceOutDto) throws Exception;
}
fallback:
@Component
@Slf4j
public class DeviceFeignClientFallbackFactory implements FallbackFactory<DeviceFeignClient> {
@Override
public DeviceFeignClient create(Throwable throwable) {
log.error("[DeviceFeignClient]服务异常:", throwable);
return new DeviceFeignClient() {
@Override
public SerializableResult<DeviceInfoOutVo> deviceInfo(DeviceOutDto deviceOutDto) {
return ResultViewUtil.genErrorSerializableResult(DeviceInfoOutVo.class, Constants.ERRCODE_SERVICE_UNAVAILABLE,Constants.ERRMSG_SERVICE_UNAVAILABLE);
}
};
}
}
controller:需要创建一个controller类实现DeviceFeignClient 接口,内部通过反射实现接口中的url请求
@RestController
public class DeviceClientController implements DeviceFeignClient {
@Resource
private OrikaBeanMapper orikaBeanMapper;
@Resource
private DeviceService deviceService;
@Override
public SerializableResult<DeviceInfoOutVo> deviceInfo(DeviceOutDto deviceOutDto) throws Exception {
TpDevice deviceInfo = deviceService.getDeviceInfoById(deviceOutDto.getDeviceId());
DeviceInfoOutVo deviceInfoOutVo = orikaBeanMapper.map(deviceInfo,DeviceInfoOutVo.class);
return ResultViewUtil.genSuccessSerializableResult(deviceInfoOutVo);
}
}
调用方只需要做到如下几步即可轻松实现feign接口调用:
1、在pom文件中引入xx-xx-api依赖
2、在调用的service实现类里面引入接口:
@Resource
private DeviceFeignClient deviceFeignClient;
3、在Application启动类里面的@ComponentScan和@EnableFeignClients两个注解需要指向xx-xx-api的包名,用于扫描feignClient和Component相关的类