springboot 中feign访问api
https://github.com/OpenFeign/feign
一、fein简介
定Denominator到HTTP API的复杂度,不区分是否支持Restful。Feign旨在通过最少的资源和代码来实现和HTTP API的连接。通过可
定制的解码器和错误处理,可以编写任意的HTTP API。
二、feign使用步骤
1、增加pom依赖
<!-- feign --> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-core</artifactId> <version>9.5.0</version> </dependency> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-slf4j</artifactId> <version>9.5.0</version> </dependency> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-hystrix</artifactId> <version>9.5.0</version> </dependency> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-jackson</artifactId> <version>9.5.0</version>
</dependency>
2、application.properties增加基础url
commonserver.redis.url=地址 commonserver.redis.timeOutMillis=100000
3.写访问api的接口
@Headers("Content-Type: application/json") @Service("feignRedisClient") public interface FeignRedisClient { @RequestLine("POST /redis/set") public Boolean set(RedisDto redisDto); @RequestLine("POST /redis/get") public Map get(RedisDto redisDto); @RequestLine("GET /mg/mgsReceive/query") public List queryMsgReceive();
@RequestLine("GET /api/v1/topics?page={page}&tab={tab}&limit={limit}&mdrender={mdrender}")
CnodeTopicsResponse getTopics(@Param("page") int page,@Param("tab") String tab, @Param("limit")int limit,@Param("mdrender") String mdrender); @RequestLine("POST /account/{id}") Account getAccountInfo(@Param("id") String id);
}
4、使用注解,配置FeignRedisClient ,并设置等候响应时间
@Slf4j @Configuration public class FeignRedisConfig { @Value("${commonserver.redis.url}") private String baseUrl ; @Value("${commonserver.redis.timeOutMillis}")
private String accessTimeOutMillis;
@Bean FeignRedisClient feignRedisClient() throws InterruptedException { try{ Integer.parseInt(accessTimeOutMillis); return HystrixFeign.builder() .decoder(new JacksonDecoder()) .encoder(new JacksonEncoder()) .setterFactory((target, method) -> new SetterFactory.Default().create(target, method). andCommandPropertiesDefaults(HystrixCommandProperties.defaultSetter(). withExecutionTimeoutInMilliseconds(Integer.parseInt(accessTimeOutMillis)))) .target(FeignRedisClient.class, this.baseUrl); }catch (Exception e){ return HystrixFeign.builder() .decoder(new JacksonDecoder()) .encoder(new JacksonEncoder()) .setterFactory((target, method) -> new SetterFactory.Default().create(target, method). andCommandPropertiesDefaults(HystrixCommandProperties.defaultSetter(). withExecutionTimeoutInMilliseconds(10000))) .target(FeignRedisClient.class, this.baseUrl); } }
}
5.配置controller
@Autowired private FeignRedisClient feignRedisClient;