spring服务方式配置okhttp3

问题

如果把OKhttp以Spring服务方式配置,就解决了从配置中心运行时刷新配置参数的问题。

OkHttpConfig.java

package com.zyl.config;

import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OkHttpConfig {
    @Bean
    public OkHttpClient.Builder builder(){
        return new OkHttpClient.Builder();
    }
    @Bean
    public ConnectionPool connectionPool(){
        return new ConnectionPool();
    }
}

配置OKhttp的构建对象。

IOkHttpService.java

package com.zyl.service;

import okhttp3.OkHttpClient;

public interface IOkHttpService {
  OkHttpClient okHttpClient();

  String getBaseUrl();
}

定义Okhttp的服务接口。

OkHttpService.java

package com.zyl.service;

import okhttp3.ConnectionPool;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@RefreshScope
@Service
public class OkHttpService implements IOkHttpService {
  private final OkHttpClient.Builder builder;

  private final ConnectionPool connectionPool;

  private Logger logger = LoggerFactory.getLogger(OkHttpService.class);
  /** 为新连接设置默认连接超时,单位毫秒 */
  @Value("${connectTimeout:10000}")
  private long connectTimeout;

  /** true表示启用连接池,false表示不启用连接池 */
  @Value("${connectionPoolEnable:true}")
  private boolean connectionPoolEnable;

  /** 第三方接口基本认证 */
  @Value("${username:zyl}")
  private String username;

  /** 第三方接口基本认证 */
  @Value("${password:8888888}")
  private String password;

  /** 第三方接口基础url */
  @Value("${baseUrl:http://api.my.com:8000/pas}")
  private String baseUrl;

  @Autowired
  public OkHttpService(OkHttpClient.Builder builder, ConnectionPool connectionPool) {
    this.builder = builder;
    this.connectionPool = connectionPool;
  }


  @Override
  public OkHttpClient okHttpClient() {
    if (connectionPoolEnable) {
      builder.connectionPool(connectionPool);
    }

    builder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);

    builder.authenticator(
        (route, response) -> {
          if (response.request().header("Authorization") != null) {
            return null; // Give up, we've already attempted to authenticate.
          }

          logger.info("Authenticating for response: " + response);
          logger.info("Challenges: " + response.challenges());
          String credential = Credentials.basic(username, password);
          return response.request().newBuilder().header("Authorization", credential).build();
        });

    List<Interceptor> networkInterceptors = builder.networkInterceptors();
    if (CollectionUtils.isEmpty(networkInterceptors)){
    	HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    	logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
    	builder.addInterceptor(logging);
    }
    return builder.build();
  }

    @Override
    public String getBaseUrl() {
        return baseUrl;
    }
}

Note: 这里的@RefreshScope不能和@Configuration混合使用,混合使用@RefreshScope并不会去Spring Cloud Config拉配置数据。

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值