81,094
社区成员
发帖
与我相关
我的任务
分享
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
@Slf4j
public class FeignClientConfig {
private OkHttpClient okHttpClient;
//注入okhttp
@Bean
public okhttp3.OkHttpClient okHttpClient(OkHttpClientFactory okHttpClientFactory,
FeignHttpClientProperties httpClientProperties) {
this.okHttpClient = okHttpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation()).connectTimeout(httpClientProperties.getConnectionTimeout(),TimeUnit.SECONDS)
.followRedirects(httpClientProperties.isFollowRedirects())
.addInterceptor(new OkHttpInterceptor())
.build();
return this.okHttpClient;
}
}
上面这个配置增加拦截器时,直接new了OkHttpInterceptor,并没有让这个拦截器提前加载,所以重新定义一个Bean,让拦截器提前加载,addInterceptor时传入这个Bean就行了。
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
@Slf4j
public class FeignClientConfig {
private OkHttpClient okHttpClient;
@Bean
public OkHttpInterceptor okHttpInterceptor(){
return new OkHttpInterceptor();
}
//注入okhttp
@Bean
public okhttp3.OkHttpClient okHttpClient(OkHttpClientFactory okHttpClientFactory,
FeignHttpClientProperties httpClientProperties) {
this.okHttpClient = okHttpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation()).connectTimeout(httpClientProperties.getConnectionTimeout(),TimeUnit.SECONDS)
.followRedirects(httpClientProperties.isFollowRedirects())
.addInterceptor(okHttpInterceptor())
.build();
return this.okHttpClient;
}
}
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public OkHttpInterceptor okHttpInterceptor (){
return new OkHttpInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(okHttpInterceptor()).addPathPatterns("/**").excludePathPatterns("/css/**")
.excludePathPatterns("/images/**")
.excludePathPatterns("/js/**")
.excludePathPatterns("/fonts/**");
}
}
启动后,仍然注入的对象都是null
附上拦截器的代码:
@Slf4j
public class OkHttpInterceptor implements HandlerInterceptor,Interceptor {
@Autowired
private ApiInitService apiInitService;
@Autowired
private RedisUtil redisUtil;
@Value("${app_id}")
String app_id;
@Value("${app_secret}")
String app_secret;
@Override
public Response intercept(Chain chain) throws IOException {
log.info("进入okhttp拦截器");
Request request = chain.request();
try {
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE);
Buffer buffer = source.getBuffer();
MediaType mediaType = responseBody.contentType();
if(isPlaintext(buffer)){
Charset charset = Charset.forName("UTF-8");
String result = buffer.clone().readString(mediaType.charset(charset));
log.info("result:"+result);
//如果token超时或不存在,则重新获取
ResponseData responseData = JSONObject.parseObject(result,ResponseData.class);
if(responseData.getCode() == CodeEnum.UNKNOWNTOKEN.getCode()){
//重新获取token
String tokenData = this.apiInitService.getToken(app_id,app_secret);
if(StringUtils.isNotEmpty(tokenData)){
//重新将token存到redis中
redisUtil.set("Authorization",tokenData);
}
}
}
return response;
}catch (Exception e){
throw e;
}
}
/**
* Returns true if the body in question probably contains human readable text. Uses a small sample
* of code points to detect unicode control characters commonly used in binary file signatures.
*/
static boolean isPlaintext(Buffer buffer) throws EOFException {
try {
Buffer prefix = new Buffer();
long byteCount = buffer.size() < 64 ? buffer.size() : 64;
buffer.copyTo(prefix, 0, byteCount);
for (int i = 0; i < 16; i++) {
if (prefix.exhausted()) {
break;
}
int codePoint = prefix.readUtf8CodePoint();
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false;
}
}
return true;
} catch (EOFException e) {
return false; // Truncated UTF-8 sequence.
}
}
private boolean bodyEncoded(Headers headers) {
String contentEncoding = headers.get("Content-Encoding");
return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
}
}