RestTemplate 是通过拦截器改变请求的URI的方式来指定服务器的,此处将通过一个自定义LoadBalanced的方式来进行说明

1.导入jar包

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

2.自定义 MyLoadBalanced 注解

import org.springframework.beans.factory.annotation.Qualifier;

import java.lang.annotation.*;

@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MyLoadBalanced {
}

3.编写配置类

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate; import java.util.Collections;
import java.util.List; @Configuration
public class MyConfig { @Autowired(required = false)
@MyLoadBalanced
private List<RestTemplate> tpls = Collections.emptyList(); @Bean
public SmartInitializingSingleton lbInitializing() {
return new SmartInitializingSingleton() {
@Override
public void afterSingletonsInstantiated() {
System.out.println("tpls 的数量:"+tpls.size());
for (RestTemplate tpl : tpls) {
List<ClientHttpRequestInterceptor> interceptors = tpl.getInterceptors();
interceptors.add(new MyInterceptor());
tpl.setInterceptors(interceptors);
} }
};
}
}

4.编写Controller测试接口 (访问 /getUser 可以发现执行的是自定义的 MyLoadBalanced  此处应该会报错,因为地址不存在,不过我们主要是为了测试是否会执行 MyLoadBalanced)

import com.idelan.ribbon.config.MyLoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; @RestController
@Configuration
public class MyController { @Bean
@MyLoadBalanced
public RestTemplate tplA() {
return new RestTemplate();
} @GetMapping(value = "/getUser")
public String getUser() {
RestTemplate restTemplate = tplA();
String json = restTemplate.getForObject("http://smart-platform-base/platform/base/getUser", String.class);
return json;
} @GetMapping(value = "/hello")
public String hello() {
return "hello world";
}
}

5.自定义拦截器来更改接口的访问地址 (@LoadBalanced 此处的逻辑会别我们复杂很多,我们只是简单模拟一下)

(1)自定义 Request 类

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest; import java.net.URI;
import java.net.URISyntaxException; public class MyRequest implements HttpRequest { HttpRequest httpRequest; public MyRequest(HttpRequest httpRequest) {
this.httpRequest = httpRequest;
} @Override
public HttpMethod getMethod() {
return httpRequest.getMethod();
} @Override
public String getMethodValue() {
return httpRequest.getMethodValue();
} @Override
public URI getURI() {
try {
URI newUri = new URI("http://localhost:8080/hello");
return newUri;
} catch (URISyntaxException e) {
e.printStackTrace();
}
return httpRequest.getURI();
} @Override
public HttpHeaders getHeaders() {
return httpRequest.getHeaders();
}
}

(2)自定义拦截器

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse; import java.io.IOException; public class MyInterceptor implements ClientHttpRequestInterceptor { @Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
System.out.println("~~~~~~~~自定义拦截器,uri:"+httpRequest.getURI());
System.out.println("旧的uri:"+httpRequest.getURI()); HttpRequest newRequest = new MyRequest(httpRequest);
System.out.println("新的uri:"+newRequest.getURI());
return clientHttpRequestExecution.execute(newRequest, bytes);
}
}

测试:可以通过访问 /getUser 接口来测试,最终会返回 /hello 接口的内容,因为我们更改了访问地址

RestTemplate 负载均衡原理的更多相关文章

  1. Nginx 负载均衡原理简介与负载均衡配置详解

    Nginx负载均衡原理简介与负载均衡配置详解   by:授客  QQ:1033553122   测试环境 nginx-1.10.0 负载均衡原理 客户端向反向代理发送请求,接着反向代理根据某种负载机制 ...

  2. 六大Web负载均衡原理与实现

    还有个姊妹篇也可以参考这个文章:LVS(Linus Virtual Server):三种负载均衡方式比较+另三种负载均衡方式, LVS 实现了负载均衡,NAT,DR,TUN zookeeper使用ZA ...

  3. 搞懂分布式技术9:Nginx负载均衡原理与实践

    搞懂分布式技术9:Nginx负载均衡原理与实践 本篇摘自<亿级流量网站架构核心技术>第二章 Nginx负载均衡与反向代理 部分内容. 当我们的应用单实例不能支撑用户请求时,此时就需要扩容, ...

  4. (转)使用LVS实现负载均衡原理及安装配置详解

    使用LVS实现负载均衡原理及安装配置详解 原文:https://www.cnblogs.com/liwei0526vip/p/6370103.html

  5. Zookeeper实现负载均衡原理

    先玩个正常的,好玩的socket编程: 服务端: 首先公共的这个Handler: package com.toov5.zkDubbo; import java.io.BufferedReader; i ...

  6. LVS实现负载均衡原理及安装配置

    LVS实现负载均衡原理及安装配置 负载均衡集群是 load balance 集群的简写,翻译成中文就是负载均衡集群.常用的负载均衡开源软件有nginx.lvs.haproxy,商业的硬件负载均衡设备F ...

  7. 使用Zookeeper实现负载均衡原理

    思路 使用Zookeeper实现负载均衡原理,服务器端将启动的服务注册到,zk注册中心上,采用临时节点.客户端从zk节点上获取最新服务节点信息,本地使用负载均衡算法,随机分配服务器. 创建项目工程 M ...

  8. 【Zookeeper】实现负载均衡原理

    一.思路 使用Zookeeper实现负载均衡原理,服务器端将启动的服务注册到,zk注册中心上,采用临时节点.客户端从zk节点上获取最新服务节点信息,本地使用负载均衡算法,随机分配服务器. 服务端启动的 ...

  9. LVS实现负载均衡原理及安装配置 负载均衡

    LVS实现负载均衡原理及安装配置 负载均衡集群是 load balance 集群的简写,翻译成中文就是负载均衡集群.常用的负载均衡开源软件有nginx.lvs.haproxy,商业的硬件负载均衡设备F ...

随机推荐

  1. Ubuntu 12.04 编译bcm93349dcm软件包

    1.准备工作操作系统:Ubuntu 12.04 获取bcm93349dcm软件包: bootloader源代码:Bootloader_2_2_0.zip CM源代码:ProdD20_BFC4.4.10 ...

  2. linux新装系统优化

    1:关掉不需要的服务 检查在3级别上哪些是自动启动的 chkconfig --list  |grep ‘3:on’

  3. spring web项目中整合netty, akka

    spring web项目中整合netty, akka 本身的web项目仍然使用tomcat/jetty8080端口, 在org.springframework.beans.factory.Initia ...

  4. 机器学习算法之——LR(未完成)

    LR的形式 sklearn中的LR模块sklearn.linear_model.LogisticRegression LR的目标函数 主要的考虑点有三个:处理什么类型的问题?是否正则以及什么正则?求解 ...

  5. python函数参数理解

    1.位置参数 函数调用时,参数赋值按照位置顺序依次赋值. e.g. def function(x): 3 return x * x 5 print function(2) 输出结果: 4 def fu ...

  6. ServletContextListener 监听器

    Servlet中的过滤器Filter是实现了javax.servlet.Filter接口的服务器端程序,主要的用途是过滤字符编码.做一些业务逻辑判断等.其工作原理是,只要你在web.xml文件配置好要 ...

  7. SQL语言分为四类,每类分别是?各包括什么?

    sqlserver(T_SQL):DDL—数据定义语言(CREATE,ALTER,DROP,DECLARE) DML—数据操纵语言(SELECT,DELETE,UPDATE,INSERT) DCL—数 ...

  8. documentFragment深入理解

    documentFragment是一个保存多个element的容器对象(保存在内存)当更新其中的一个或者多个element时,页面不会更新.只有当documentFragment容器中保存的所有ele ...

  9. 主成分分析(PCA)模型概述

    数据降维 降维是对数据高维度特征的一种预处理方法.降维是将高维度的数据保留下最重要的一些特征,去除噪声和不重要的特征,从而实现提升数据处理速度的目的.在实际的生产和应用中,降维在一定信息损失范围内,可 ...

  10. 吴裕雄--天生自然 python数据分析:基于Keras使用CNN神经网络处理手写数据集

    import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mp ...