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

配置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 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) {
    this.builder = builder;
  }

  @Override
  public OkHttpClient okHttpClient() {
    if (connectionPoolEnable) {
      builder.connectionPool(new 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拉配置數據。

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章