负载均衡的实例时是在eureka实例的基础上搭建的。
eureka的实例
https://blog.csdn.net/wangyunzhao007/article/details/105776190
除此之外,我们还需要一个注册中心的同名服务端,然后在客户端使用测试类进行调用测试即可。
同名客户端
和eureka博客中的服务端配置基本相同,只需修改一下端口号即可。然后启动,然后查看在localhost:10086的页面,如图:
然后改造客户端,我们需要建立一个测试类。
1.首先增加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
然后增加测试类:
@SpringBootTest(classes= ServiceConsumerApplication.class)
//@RunWith(SpringRunner.class)
public class RibbonLoadBalanceTest {
@Autowired
private RibbonLoadBalancerClient client;
@Test
public void test(){
for (int i = 0; i <50 ; i++) {
ServiceInstance instance = this.client.choose("service-provider");
System.out.println(instance.getHost()+":"+instance.getPort());
}
}
}
然后启动测试类,因为并没有配置yml中的属性,ribbon默认是轮询访问两个客户端:
当我们添加了yml中的配置后
整个服务端的yml配置如下:
server:
port: 80
spring:
application:
name: service-consumer
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka/
registry-fetch-interval-seconds: 5
fetch-registry: true #开启拉取服务
service-provider: #服务提供方的id
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #策略为随机
yml文件配置了负载均衡策略是随机,执行结果如下: