openfeign配置代理服务器

本文介绍了如何在Spring Boot应用中启用Feign客户端,并通过自定义OkHttpClient配置代理服务器,包括IP、端口和认证。重点在于`allow-bean-definition-overriding`配置项和`@EnableFeignClients`注解的使用。
摘要由CSDN通过智能技术生成

目录

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

第二步:配置Bean


 

第一步:配置文件允许覆盖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<Proxy> proxyList = new ArrayList<>(1);
            proxyList.add(proxy);
            builder.proxySelector(new ProxySelector() {
                //限制域
                Set<String> domainList;
                @Override
                public List<Proxy> 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) {
                }
            });*/
        }
    }
}

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文子阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值