springcloud学习笔记(三)客户端负载平衡器:Ribbon
Ribbon是一个客户端负载均衡器,它可以很好地控制HTTP和TCP客户端的行为。
在上一篇笔记的基础上我们把service2加一个节点(改下端口号)然后启动客户端和服务端:
可以看到两个节点 都启动了,现在我们在cloud-test使用ribbon调用cloud-test2
在RestTemp上加注解
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
然后开始调用:
@RequestMapping("/")
public String sayhello() {
String s=restTemplate.getForObject("http://cloud-test2/hello",String.class);
System.out.println(s);
return "hello";
}
@RequestMapping("/hello") public String sayhe() { System.out.println("进来了 hello"); return "hello"; }
看结果:
两个节点都有访问到。由于我代码中加了自定义的负载规则,所以访问是随机的。ribbon hello word 完成!