拦截feign并对数据进行转发到线上服务方案(全网首创)

业务需求:
主要是想实现本地开发的服务能自动路由到测试的服务,不用自己本地起一大堆服务,由于测试的服务器只开放了一个nginx端口,没有对外暴露服务,只能自己去实现转发,
原理说明:
通过自己反复研究源码最终摸索出了拦截feign的终于方案,通过实现Client 即可,然后自己用httpclient进行请求转发,之前尝试过ribbon自定义路由规则,但是他不能实现自定url前缀,和feign拦截器而拦截器只能修改请求头垃圾,不能修改url,所以这两个方案都被pass了,最后的实现方案也是自己反复调试源码得到的,

缺陷:
此类目前只对feign服务调用有效,而对zuul网关转发无效(zuul网关路由时会首先加载ribbon的loadbance进行路由,跟feign没什么事),由于时间关系,暂时先不搞网关的拦截,把网关用本地nginx来替代,来实现转发

其他本地调用测试线上比较好的方案:
1.vpn 可以让本地机器与线上形成局域网,天然的本地调用线上服务,目前是最好的方案

2.线上开放所有的微服务服务端口,然后在@feignclient 指定url,如果可以对外开放那么多端口,也可以

package com.central.common.ribbon.config;

import cn.hutool.core.convert.Convert;
import feign.Client;
import feign.Request;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;



//开发环境时调用线上服务流程:
// 1:feign先转发到本地的nginx
//2:本地nginx转发到测试线上的nginx
@Profile("dev")
@Component
@Slf4j
public class LocalDevFeignClient implements  Client {
    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        String url=request.url();
        String str1=""; //http还是https
        if (url.startsWith("http://")){
            str1="http://";
            url=url.replace("http://","");
        }else if(url.startsWith("https://")){
            str1="https://";
            url=url.replace("https://","");
        }
        Response response =null;
        //log.info(url.substring(0,url.indexOf("/")));

        HttpClient httpclient = HttpClientBuilder.create().build();
        if (request.method().equals("GET")){
            HttpGet httpGet=new HttpGet(str1+"127.0.0.1:7432/"+url);
            log.info("转发get请求:"+url);
            HttpResponse httpResponse=httpclient.execute(httpGet);
//            BufferedReader rd = new BufferedReader(
//                    new InputStreamReader(httpResponse.getEntity().getContent()));
//            StringBuffer result = new StringBuffer();
//            String line = "";
//            while ((line = rd.readLine()) != null) {
//                result.append(line);
//            }
            Header[]  headers=httpResponse.getAllHeaders();

            response= Response.builder().headers(copyHeaderToFeign(httpResponse.getAllHeaders())).status(httpResponse.getStatusLine().getStatusCode()).body(httpResponse.getEntity().getContent(),Convert.toInt(httpResponse.getEntity().getContentLength())).build();

        }else {
            log.info("转发post请求:"+url);

        }


        return  response;
    }

    public Map<String, Collection<String>>  copyHeaderToFeign(  Header[]  headers){
        Map<String, Collection<String>> repHeader=new HashMap<>();
        for (Header e:headers){
            List<String> list=new ArrayList<>();
            list.add(e.getValue());
            repHeader.put(e.getName(),list);
        }

        return repHeader;
    };

    public static void main(String[] args) {
        String url="http://user-center/users/name/z2w";
        if (url.startsWith("http://")){
            url=url.replace("http://","");
        }else if(url.startsWith("https://")){
            url=url.replace("https://","");
        }

       log.info(url.substring(0,url.indexOf("/")));  ;

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以通过在Feign客户端上添加Resilience4j的拦截器来实现熔断逻辑。下面是一些步骤来实现这个过程: 1. 首先,确保你已经添加了Resilience4j的依赖到你的项目中。你可以在Maven或者Gradle配置文件中添加以下依赖: ```xml <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring-cloud2</artifactId> <version>1.6.1</version> </dependency> ``` 2. 创建一个实现Feign的RequestInterceptor接口的类,用于拦截Feign的请求。以下是一个示例: ```java import feign.RequestInterceptor; import feign.RequestTemplate; import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Resilience4jFeignInterceptor implements RequestInterceptor { private final CircuitBreakerRegistry circuitBreakerRegistry; @Autowired public Resilience4jFeignInterceptor(CircuitBreakerRegistry circuitBreakerRegistry) { this.circuitBreakerRegistry = circuitBreakerRegistry; } @Override public void apply(RequestTemplate requestTemplate) { String serviceName = requestTemplate.feignTarget().name(); circuitBreakerRegistry.circuitBreaker(serviceName).executeRunnable(() -> { // 在这里执行你的Feign请求 requestTemplate.header("Authorization", "Bearer your-token"); }); } } ``` 3. 在你的Feign客户端接口上添加`configuration`属性,使用上述的拦截器类。例如: ```java import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "your-service-name", configuration = Resilience4jFeignInterceptor.class) public interface YourFeignClient { @GetMapping("/your-endpoint") String yourFeignMethod(); } ``` 这样,当你使用`YourFeignClient`接口的方法发送请求时,请求将会通过Resilience4j的断路器进行拦截和熔断处理。 请注意,上面的示例中使用了`CircuitBreakerRegistry`来获取相应的断路器实例。你需要根据你的实际需求进行配置和使用Resilience4j的断路器。另外,你还可以根据需要添加其他的Resilience4j功能,如限流、重试等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_令狐大侠_

觉的文章对你有用,鼓励一下吧

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

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

打赏作者

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

抵扣说明:

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

余额充值