spring服务方式配置okhttp3

原创
2018/12/10 11:32
阅读数 168

问题

如果把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();
        });

    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 评论
1 收藏
0
分享
返回顶部
顶部