业务需求:
主要是想实现本地开发的服务能自动路由到测试的服务,不用自己本地起一大堆服务,由于测试的服务器只开放了一个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("/"))); ;
}
}