前言
调用第三方接口有很多的工具类,httpclient,okhttp等,这篇文章讲的是Feign调用第三方接口。直接上代码吧!
pom文件
<!--openfein的依赖-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>11.2</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>11.2</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>11.0</version>
</dependency>
yaml
intel-service:
http:
apiKey: 2F3t4Zn0YZm25ytExbBX0Vd2xDZqcYGX1
apiInstance:
user:
envConstant: dev
host: http://10.0.4.90
port: 9100
context-path: /es
配置文件
FeignConfig 主要配置Feign的连接,Constant.COLON其实就是“:”;
@Configuration
public class FeignConfig {
@Autowired
private ServiceProperties serviceProperties;
/**
* Fegin约束
*/
@Bean
public Contract contract() {
return new Contract.Default();
}
@Bean
public PortalUserFeignService portalUserFeignService() {
ServiceProperties.ServiceInstance si = serviceProperties.getApiInstance().get(InnerServiceConfig.USER);
return Feign.builder()
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.options(this.options())
.logger(new Slf4jLogger())
.logLevel(Logger.Level.FULL)
.requestInterceptor(template -> template.header("ApiKey", serviceProperties.getApiKey())
.header("Content-Type", "application/json"))
.target(PortalUserFeignService.class, si.getHost().concat(Constant.COLON).concat(si.getPort()).concat(serviceProperties.handleEnv(si)).concat(si.getContextPath()));
}
/**
* connectTimeoutMillis=2000 链接超时时间readTimeoutMillis=10000 响应超时时间,如果超过10秒没有接过发起下一次请求
*/
private Request.Options options() {
return new Request.Options(2000, 10000);
}
}
InnerServiceConfig :我们可能不止一个第三方调用接口,这里相当于是配置多个
@Configuration
@EnableConfigurationProperties(ServiceProperties.class)
public class InnerServiceConfig {
public static final String USER = "user";
@Bean
@ConditionalOnProperty(name = "intel-service.http.apiInstance.user.host")
public UserServiceApi userServiceApi(ServiceProperties sip) {
UserServiceApi userServiceApi = new UserServiceApi();
fillApis(sip, userServiceApi, USER);
return userServiceApi;
}
private void fillApis(ServiceProperties sip, UserServiceApi api, String serviceName) {
ServiceProperties.ServiceInstance si = sip.getApiInstance().get(serviceName);
Map<String, String> suffixes = si.getSuffixes();
Set<String> configuredKeys = suffixes.keySet();
api.setApiKey(sip.getApiKey());
api.setBaseUrl(
si.getHost()
.concat(Constant.COLON)
.concat(si.getPort())
.concat(sip.handleEnv(si))
.concat(si.getContextPath()));
for (String key : configuredKeys) {
// 同名配置项匹配
try {
Field field = api.getClass().getDeclaredField(key);
field.setAccessible(true);
field.set(api, suffixes.get(key));
} catch (Exception e) {
// ignore when no field matches.
}
}
}
}
ServiceProperties:不同环境可能有不同的配置文件,这个主要是根据不同的生产环境进行配置
@ConfigurationProperties(prefix = "intel-service.http")
public class ServiceProperties {
private String apiKey;
private Map<String, ServiceInstance> apiInstance = new HashMap();
public ServiceProperties() {
}
public Map<String, ServiceInstance> getApiInstance() {
return this.apiInstance;
}
public void setApiInstance(Map<String, ServiceInstance> apiInstance) {
this.apiInstance = apiInstance;
}
public String getApiKey() {
return this.apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String handleEnv(ServiceInstance instance) {
switch (instance.envConstant) {
case sit:
return "/sit-api";
case uat:
return "/uat-api";
case prod:
return "/prod-api";
default:
return "";
}
}
static enum EnvConstant {
dev,
sit,
uat,
prod;
private EnvConstant() {
}
}
public static class ServiceInstance {
private EnvConstant envConstant;
private String contextPath;
private String host;
private String port;
private Map<String, String> suffixes;
public ServiceInstance() {
this.envConstant = ServiceProperties.EnvConstant.dev;
}
public String getContextPath() {
return this.contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return this.port;
}
public void setPort(String port) {
this.port = port;
}
public Map<String, String> getSuffixes() {
return this.suffixes;
}
public void setSuffixes(Map<String, String> suffixes) {
this.suffixes = suffixes;
}
public EnvConstant getEnvConstant() {
return this.envConstant;
}
public void setEnvConstant(EnvConstant envConstant) {
this.envConstant = envConstant;
}
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserServiceApi{
/*
鉴权字段
*/
private String apiKey;
/*
url
*/
private String baseUrl;
}
第三方接口
public interface PortalUserFeignService {
/**
*
* @return
*/
@RequestLine("GET /doc/getById?id={id}")
Result getById(@Param(value = "id") String id);
}
调用
@RestController
@Api(tags = "远程调用")
@RequestMapping("/feign")
public class FeignController {
@Autowired
PortalUserFeignService portalUserFeignService;
@GetMapping("/test")
@ApiOperation(value = "远程调用测试")
public Result test(String id){
return portalUserFeignService.getById(id);
}
}
结果