远程调用Feign使用
pom Maven依赖
<!-- https://mvnrepository.com/artifact/io.github.openfeign/feign-core -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>10.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.github.openfeign/feign-jackson -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
<version>10.1.0</version>
</dependency>
ApiHostConfig配置类
使用lombok简化get set操作
示例
@Configuration
@Data
class ApiHostConfig{
/**
* 用户中心服务端接口地址
*/
@Value(value = "${user.center.api.host}")
private String userCenterApiHost;
}
用于配置远程主机value值和properties文件中的地址对应相应的要调用的远程地址
示例
user.center.api.host = http://api.user.xxxx.in
FeignBuidlerfeign方式调用接口构造类
示例
@Component
public class FeignBuidler{
@Autowired
private ApiHostConfig apiHostConfig;
//用于对httprequest对象的拦截处理
@Autowired
private FeignRequestInterceptor requestInterceptor;
/**
* 构造用户中心的远程接口调用
*
* @return
*/
@Bean(name = "userRemoteService")
public UserRemoteService buildUserService() {
return buildService(UserRemoteService.class, apiHostConfig.getUserCenterApiHost());
}
/**
* 构造远程调用接服务接口
*
* @param t 待构造的类型
* @param apiHost 接口host
* @param <T>
* @return
*/
private <T> T buildService(Class<T> t, String apiHost) {
T instance = Feign.builder()
.encoder(new JacksonEncoder())
.decoder(new JacksonDecoder())
.options(new Request.Options(1000, 3500))
.retryer(new Retryer.Default(5000, 5000, 3))
.requestInterceptor(this.requestInterceptor)
.target(t, apiHost);
return instance;
}
}
FeignRequestInterceptor
用于httprequest对象的拦截处理
示例
@Slf4j
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
/**
* http headers穿透
*
* @param template
*/
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
template.header(name, values);
}
}
}
}
UserRemoteService 调用用户中心类编写
示例
public interface UserRemoteService {
/**
* 用户登录接口 post方式访问
*
* @param userLoginInfoRequest userLoginInfoRequest
* @return Result
*/
@Headers({"Content-Type: application/json", "Accept: application/json"})
@RequestLine("POST /user/login")
Result doLogin(UserLoginInfoRequest userLoginInfoRequest);
/**
* 查询当前登录用户身份证照片
*GET方式访问
*
* @return
*/
@RequestLine("GET /user/idcard")
Result<UserInfoExtVO> getUserInfoIdCard();
/**
* 查询banner列表
*GET方式访问携带id
* @param systemId
* @param terminalType
* @return
*/
@RequestLine("GET /banner/list?systemId={systemId}&terminalType={terminalType}")
Result<List<Banner>> getBanners(@Param(value = "systemId") Short systemId, @Param(value = "terminalType") Short terminalType);
}