本文描述在没有时用Eruka 注册中心如何使用ribbon ,feign分别进行负载均衡的使用方法,文中有个服务
http://localhost:8081/ribbon/hello
分别输出
{"id":null,"username":"8081usename","name":"8081name","age":1,"balance":1}
http://localhost:8084/ribbon/hello
{"id":null,"username":"8084usename","name":"8084name","age":1,"balance":1}
代码在
https://gitee.com/chinadeng/ribbontest.git
和
https://gitee.com/chinadeng/proxytest.git
一,ribbon 负载均衡
1.在application.properties 配置ribbon 获取服务地址
#配置Ribbon能访问 的微服务节点,多个节点用逗号隔开
microservice-provider-user.ribbon.listOfServers=localhost:8081,localhost:8084
2 配置ribbon 策略,使用 RestTemplate 进行http请求
@Configuration
public class FooConfiguration {
@Bean
public ZonePreferenceServerListFilter serverListFilter() {
ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter();
filter.setZone("myTestZone");
return filter;
}
@Bean
public IPing ribbonPing() {
return new PingUrl();
}
//
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
3. 在相应请求中注入RestTemplate 实列进行请求
User use =this.restTemplate.getForObject(
"http://microservice-provider-user/ribbon/hello",
User.class);*/
这是请求 尼就会发现可以负载均衡了,客户端自动路由了
二 使用feign 进行请求.
1.在application.properties 配置ribbon 获取服务地址
#配置Ribbon能访问 的微服务节点,多个节点用逗号隔开
microservice-provider-user.ribbon.listOfServers=localhost:8081,localhost:8084
2.配置feign 接口
@FeignClient(value = "person-service") public interface PersonClient { @RequestMapping(method = RequestMethod.POST, value = "/person") String person(@RequestParam(value = "firstname") String firstname, @RequestParam(value = "lastname") String lastname); }
接入完毕,你会发现完全可以自动路由了