openfeign配置代理服务器

第一步:配置文件允许覆盖Bean

spring:
  main:
    allow-bean-definition-overriding: true

第二步:配置Bean

package com.ciih.refine.config;

import okhttp3.*;
import org.springframework.cloud.commons.httpclient.DefaultOkHttpClientFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;

@Configuration
//配置openfein接口的文件件路径
@EnableFeignClients(basePackages = "com.ciih.refine.server")
public class Config {

    @Bean
    public OkHttpClientFactory okHttpClientFactory(OkHttpClient.Builder builder) {
        return new ProxyOkHttpClientFactory(builder);
    }

    static class ProxyOkHttpClientFactory extends DefaultOkHttpClientFactory {

        public ProxyOkHttpClientFactory(OkHttpClient.Builder builder) {
            super(builder);
            //配置IP、端口
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("190.168.1.1", 8080));
            builder.proxy(proxy);

            builder.proxyAuthenticator(new Authenticator() {
                @Override
                public Request authenticate(Route route, Response response) throws IOException {
                    //设置代理服务器账号密码
                    String credential = Credentials.basic("admin", "admin");
                    return response.request().newBuilder()
                            .header("Proxy-Authorization", credential)
                            .build();
                }
            });
            //如果要配置限制域则加上下面
            /*List proxyList = new ArrayList<>(1);
            proxyList.add(proxy);
            builder.proxySelector(new ProxySelector() {
                //限制域
                Set domainList;
                @Override
                public List select(URI uri) {
                    if (uri == null || !domainList.contains(uri.getHost())) {
                        return Collections.singletonList(Proxy.NO_PROXY);
                    }
                    return proxyList;
                }

                @Override
                public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                }
            });*/
        }
    }
}

你可能感兴趣的:(java,服务器,开发语言)