spring服務方式配置okhttp3

問題

若是把OKhttp以Spring服務方式配置,就解決了從配置中心運行時刷新配置參數的問題。java

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的構建對象。spring

IOkHttpService.java

package com.zyl.service;

import okhttp3.OkHttpClient;

public interface IOkHttpService {
  OkHttpClient okHttpClient();

  String getBaseUrl();
}

定義Okhttp的服務接口。api

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拉配置數據。ide

參考

相關文章
相關標籤/搜索