RestTemplate 是 spring-web 模块提供的一个执行同步http请求的客户端,底层依赖的是 JDK HttpURLConnection, Apache HttpComponents 和 OkHttp3 等,在将请求提交给这些底层模块之前,提供了扩展点:通过ClientHttpRequestInterceptor接口的实现类对请求进行拦截处理。这篇文章是 Spring Cloud Loadbalancer 模块学习的前置文章。因为 Spring Cloud loadbalancer 是通过 ClientHttpRequestInterceptor 对 RestTemplate 进行负载均衡的。因此需要对 ClientHttpRequestInterceptor 有所了解。
- 需要注意的是,根据文档显示从Spring 5.0开始 RestTemplate 已经进入维护的阶段,目前主推的是org.springframework.web.reactive.client.WebClient,支持异步请求。
ClientHttpRequestInterceptor 接口是比较简单
public interface ClientHttpRequestInterceptor {
ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException;
}
涉及的其他类如下,本质上是对HTTP协议的抽象。
// HttpRequest 代表了一个 http 请求体,包含了请求行(HttpMethod,URI),请求头
public interface HttpRequest extends HttpMessage {
@Nullable
default HttpMethod getMethod() {
return HttpMethod.resolve(getMethodValue());
}
String getMethodValue();
URI getURI();
}
public interface HttpMessage {
HttpHeaders getHeaders();
}
public class HttpHeaders implements MultiValueMap<String, String>, Serializable {
// 省略
}
ClientHttpResponse 代表了http请求的响应,也是包含了状态码,响应头,响应体。
public interface ClientHttpResponse extends HttpInputMessage, Closeable {
HttpStatus getStatusCode() throws IOException;
int getRawStatusCode() throws IOException;
String getStatusText() throws IOException;
@Override
void close();
}
public interface HttpInputMessage extends HttpMessage {
InputStream getBody() throws IOException;
}
public interface ClientHttpRequestExecution {
ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOException;
}
ClientHttpRequestExecution 主要是用于构建拦截器调用链,并通过调用栈的形式执行拦截器。
@FunctionalInterface
public interface ClientHttpRequestExecution {
ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOException;
}
实现类如下:
class InterceptingClientHttpRequest extends AbstractBufferingClientHttpRequest {
private final List<ClientHttpRequestInterceptor> interceptors;
private final ClientHttpRequestFactory requestFactory;
private class InterceptingRequestExecution implements ClientHttpRequestExecution {
private final Iterator<ClientHttpRequestInterceptor> iterator;
public InterceptingRequestExecution() {
this.iterator = interceptors.iterator();
}
@Override
public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOException {
if (this.iterator.hasNext()) {
// 执行调用链
ClientHttpRequestInterceptor nextInterceptor = this.iterator.next();
return nextInterceptor.intercept(request, body, this);
}// 调用链结束,回到主流程,获取底层的 ClientHttpRequest,并执行。
else {
HttpMethod method = request.getMethod();
Assert.state(method != null, "No standard HTTP method");
ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), method);
request.getHeaders().forEach((key, value) -> delegate.getHeaders().addAll(key, value));
if (body.length > 0) {
if (delegate instanceof StreamingHttpOutputMessage) {
StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) delegate;
streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(body, outputStream));
}
else {
StreamUtils.copy(body, delegate.getBody());
}
}
return delegate.execute();
}
}
}
// 省略..
}
拦截器的应用还是比较简单的,只需往 RestTemplate 实例添加拦截器即可。
public class InterceptorTest {
public static void main(String[] args) {
ClientHttpRequestInterceptor i1 = new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
System.out.println("拦截器1开始。。。");
ClientHttpResponse execute = execution.execute(request, body);
System.out.println("拦截器1结束。。。");
return execute;
}
};
ClientHttpRequestInterceptor i2 = new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
System.out.println("拦截器2开始。。。");
ClientHttpResponse execute = execution.execute(request, body);
System.out.println("拦截器2结束。。。");
return execute;
}
};
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(i1);
restTemplate.getInterceptors().add(i2);
String forObject = restTemplate.getForObject("http://www.baidu.com", String.class);
System.out.println(forObject);
}
}
执行以上代码,输出如下:
- 拦截器1开始。。。
- 拦截器2开始。。。
- 拦截器2结束。。。
- 拦截器1结束。。。
我们作出一点改变,通过拦截器来实现负载均衡。
public class InterceptorTest {
static class Mywraper extends HttpRequestWrapper{
private String url;
public Mywraper(HttpRequest request,String url) {
super(request);
this.url = url;
}
@Override
public URI getURI() {
try {
return new URI(url);
} catch (URISyntaxException e) {
}
return null;
}
}
public static void main(String[] args) {
String[] loabancerhost = {"https://www.baidu.com", "https://www.sina.com.cn"};
AtomicInteger times = new AtomicInteger(0);
ClientHttpRequestInterceptor i1 = new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
int length = loabancerhost.length;
int i = times.getAndIncrement() % length;
//因为 HttpRequest 和 URI 不提供修改功能,因此需要借助 HttpRequestWrapper 对request进行包装
Mywraper mywraper = new Mywraper(request, loabancerhost[i]);
ClientHttpResponse execute = execution.execute(mywraper, body);
return execute;
}
};
ClientHttpRequestInterceptor i2 = new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
System.out.println("第"+times+"次请求的host为: "+request.getURI());
ClientHttpResponse execute = execution.execute(request, body);
return execute;
}
};
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(i1);
restTemplate.getInterceptors().add(i2);
for (int i = 10; i > 0; i--) {
restTemplate.getForObject("http://www.baidu.com", String.class);
}
}
}
- 第1次请求的host为: https://www.baidu.com
- 第2次请求的host为: https://www.sina.com.cn
- 第3次请求的host为: https://www.baidu.com
- 第4次请求的host为: https://www.sina.com.cn
- 第5次请求的host为: https://www.baidu.com
- 第6次请求的host为: https://www.sina.com.cn
- 第7次请求的host为: https://www.baidu.com
- 第8次请求的host为: https://www.sina.com.cn
- 第9次请求的host为: https://www.baidu.com
- 第10次请求的host为: https://www.sina.com.cn
至此,如何通过 InterceptingClientHttpRequest 进行 RestTemplate 负载均衡介绍完毕,本质上原理还是很简单的。只需要通过拦截器修改URI即可。
使用Ruby1.8.6/Rails2.3.2我注意到在我的任何ActiveRecord模型类上调用的任何方法都返回nil而不是NoMethodError。除了烦人之外,这还破坏了动态查找器(find_by_name、find_by_id等),因为即使存在记录,它们也总是返回nil。不从ActiveRecord::Base派生的标准类不受影响。有没有办法追踪在ActiveRecord::Base之前拦截method_missing的是什么?更新:切换到1.8.7后,我发现(感谢@MichaelKohl)will_paginate插件首先处理method_missing。但是will_pa
我目前有一个父类(superclass),它有一个函数,我希望所有子类在它的每个函数中调用该函数。该函数的行为应该像rails中的before_filter函数,但我不确定如何去实现before_filter。这是一个例子classSuperclassdefbefore_each_methodputs"BeforeMethod"#thisissupposedtobeinvokedbyeachextendingclass'methodendendclassSubclass 最佳答案 这是一种方法:classSuperclassdefb
我正在使用rails3.0.3、ruby1.9.2-p180、邮件(2.2.13)。我正在尝试设置邮件拦截器,但出现以下错误/home/abhimanyu/Aptana_Studio_3_Workspace/delivery_health_dashboard_03/config/initializers/mailer_config.rb:16:in`':uninitializedconstantDevelopmentMailInterceptor(NameError)我该如何解决?我使用的代码如下所示:config/initializer/mailer_config.rbActionM
我的angular-cli(v1.5.1,angularv5)应用程序中有以下两个环境:开发产品Dev使用模拟数据,我提供了一个http拦截器。Pro使用实时休息api。我如何在dev上提供http拦截器,而不是在pro上?我已经尝试了以下方法,但它不起作用:{provide:HTTP_INTERCEPTORS,useFactory:()=>{if(environment.useMockBackend===true){returnMockHttpInterceptor;}returnfalse;},multi:true} 最佳答案
我正在使用Capybara、Cucumber和Poltergeist。我正在测试附加到表单提交按钮的JavaScript函数,该函数旨在捕获提交事件并阻止它(在后台执行AJAX请求)。使用和不使用AJAX,页面最终看起来都一样,但AJAX方法要快得多,并且不会中断浏览体验等。我可以做些什么来测试表单确实没有提交,并且更改是动态AJAX调用而不是重新加载的结果? 最佳答案 @jules答案的修改版本:describe"Mypage",:jsdoit"reloadswhenitshould"dovisit"/"expect_page_t
我正在尝试编写一个拦截器以使用Angular向所有HTTP请求添加一个token。我大致使用这里给出的食谱-https://thinkster.io/interceptors因此代码使用了http模块工厂和一个tokenInterceptor()函数。我可以成功地将token作为header添加到请求中-但现在当它通过拦截器时,它会被某种CORS阻塞机制阻塞。我在Chrome控制台中收到此错误-XMLHttpRequestcannotloadhttp://127.0.0.1:/.Responsetopreflightrequestdoesn'tpassaccesscontrolchec
我想将一些副作用与每个数组访问器相关联,例如a[i]。例如,如果副作用是向控制台写入消息,则以下程序:vararray=[1,2,3]vartotal=0;for(variinarray){total+=array[i]}console.log(total);应该返回如下输出:1//accessa[0]2//accessa[1]3//accessa[2]6//printoriginaltotal如果我对拦截数组方法push感兴趣,我会使用此博客中的技术post并提供了一个拦截器:var_push=Array.prototype.push;Array.prototype.push=fun
是否可以使用javascript拦截从页面发出的每个请求?即单击链接、加载图像、ajax请求... 最佳答案 一句话,没有。没有任何地方可以Hook以获取所有请求。话虽如此,您可以使用javascript在链接上放置事件处理程序,查看图像标签的src属性等。没有“通用”的方式来连接所有AJAX请求-这取决于您使用的库。还有其他需要考虑的,比如CSS背景图片,Flash(如果一个flash文件发出请求怎么办?)。如果可能,您应该使用浏览器本身(例如Firebug)或代理(例如Fiddler)或数据包嗅探器(例如Ethereal...现
我遇到的问题是,当我尝试执行类似以下代码的操作时,窗口将被弹出窗口阻止程序阻止。我正在使用getScript以便我可以发出跨域请求。我正在使用jQuery1.4.2来执行以下操作。将被阻止的代码示例://Codethatgetsblockedbypop-upblockers$(document).ready(function(){$(".popup").click(function(){$.getScript("URL_To_A_Javascript_File",function(){window.open("dynamicURL","_blank");});});});越过拦截器但未
有什么方法可以拦截通过jquery发出的ajax请求,向其中插入额外的变量吗?我知道.ajaxStart()允许您注册一个回调,该回调在ajax请求开始时触发一个事件,但我正在寻找一种方法来取消该ajax请求,如果它满足某些条件(例如url),在其内容中插入更多变量,然后提交。这是用于第三方软件的插件,其自身代码无法直接更改。编辑:看起来像.ajaxSetup()允许您设置一些与ajaxRequests相关的全局变量。如果我注册了一个beforeSend函数,该函数是否能够取消请求以在满足特定条件时做出不同的请求? 最佳答案 想通了