@FeignClient用于Nacos微服务间的接口调用
依赖:
<!-- spring-boot启动依赖 -->
<!-- 提供者 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- openFeign -->
<!-- 消费者-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
yml配置
feign:compression:response:enabled: truerequest:enabled: truemime-types: text/xml,application/xml,application/jsonmin-request-size: 2048circuitbreaker:enabled: trueclient:config:default:connectTimeout: 5000readTimeout: 5000loggerLevel: basic
提供者创建RESTful接口,controller接口 @RestController @GetMapping("/url")
消费者创建feign目录,创建Interface ManagementClient
//name 填写
//spring:
//application:
// name: management
//springboot的服务名
//fallback填写实现类,用于接口回调,接口异常时返回保底数据
@FeignClient(name = "management", fallback = ManagementClientFallback.class)
public interface ManagementClient {@PostMapping("/url")OperaResponse selectList(@RequestBody IdRequest request);
}
/feign/impl,创建ManagementClientFallback类
/*** fallback是在远程服务调用失败时,向调用方返回一个备用(回退)响应的机制*/
@Component
public class ManagementClientFallback implements ManagementClient {@Overridepublic OperaResponse selectList(IdRequest request) {return OperaResponse.error(ErrStatus.FEIGN_ERROR);}
}
创建ClientUtil用于调用Client方法,service层依赖注入Client,将Client对象和参数传给ClientUtil方法
@Autowiredprivate ChannelManagementClient channelManagementClient;
public class ClientUtil {private ClientUtil(){}public static List<Response> selectList(ManagementClient client, Integer Id){IdRequest request = new IdRequest();request.setId(id);OperaResponse operaResponse = client.selectList(request);if(operaResponse.getData() == null){return new ArrayList<>();}List<Response> list = JSONObject.parseArray(JSONObject.toJSONString(operaResponse.getData()), Response.class);return list == null ? new ArrayList<>() : list;}
}