上篇博客【使用Spring Cloud搭建高可用服务注册中心】中我们介绍了如何使用Spring Cloud搭建一个高可用服务注册中心,如此就能解决单点故障的问题 , 由于本人的电脑不是很流畅 , 以后的博库会使用单机版的Eureka,大家可以使用高可用的Eureka搭建 . 好了 , 废话不多说,开始本章的学习!
先介绍一下Ribbon,ribbon是Netfilx发布的开源项目,其功能主要提供客户端软件的负载均衡算法, 将Netfilx的中间层服务连接在一起,Ribbon的客户端组件提供了一系列的完善的配置项,例如连接超时,重试等.
1.引入ribbon的jar
- user工程中引入ribbon的jar
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.tianxiaobin</groupId>
<artifactId>springcloud-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>springcloud-eureka-user</artifactId>
<name>user客户端</name>
<dependencies>
<!-- ribbon负载均衡启动包 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<!-- eureka的启动包 -->
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
2.添加注解
- 在user工程的启动类中 , 注入restTemplate的时候添加@Loadbalanced注解
/**
* @ClassName: UserApplication
* @Description: 客户端的启动类
* @author: 田晓斌
* @date: 2019年4月17日 下午6:23:10
*/
@EnableEurekaClient
@SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
3.修改userController
这样使用ribbon负载均衡已经成功了 , 为了方便测试 , 我们在order工程中编写一个监听类 , 用来看user访问order工程的时候 具体走的是哪个端口:
- ServiceInfoUtil如下:
/**
* @ClassName: ServiceInfoUtil
* @Description: 监听服务实例端口的工具类
* @author: 田晓斌
* @date: 2019年4月22日 上午11:46:47
*/
@Configuration
public class ServiceInfoUtil implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
// 声明event对象 , 该对象用于获取运行服务器的本地端口
private static EmbeddedServletContainerInitializedEvent event;
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
ServiceInfoUtil.event = event;
}
// 获取端口号
public static Integer getPort() {
return event.getEmbeddedServletContainer().getPort();
}
}
- 在orderController中添加代码
4.测试
我们启动eureka和user工程 , 之后将order工程的端口号改为8002和8003,分别启动.
eureka如下:
我们访问10次之后发现: