购买
下载掌阅APP,畅读海量书库
立即打开
畅读海量书库
扫码下载掌阅APP

4.1 使用Ribbon

这个实例会涉及一个Eureka注册中心服务端、两个服务提供方、一个服务消费方。注册中心将继续使用上文中已经实现过的Eureka。启动两个myprovider,包含SayHello功能的服务提供方并注册在Eureka上。

接下来,对上文中Eureka客户端的代码进行改造。


@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
@Slf4j
@RestController
public class EurekaClientApplication2 {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    @Autowired
    private LoadBalancerClient client;
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping(value = "/sayHello" ,method = RequestMethod.GET)
    public String sayHello(String name) {
        ServiceInstance instance =  client.choose("myprovider");
        log.info(instance.getUri().toString());
        String result=restTemplate.getForObject(instance.getUri().toString()+"/sayHello?name="+name,String.class);
        return  result+"from "+instance.getPort();
    }
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication2.class, args);
    }
}

将DiscoveryClient改为LoadBalancerClient,并调用其choose方法,会使原先的得到一个ServiceInstance集合变为得到单个ServiceInstance实例。

之后,返回ServiceInstance的端口来区分我们的两个服务提供方,接下来用浏览器请求 http://localhost:8081/sayHello?name=test


hello testfrom 8084
hello testfrom 8085

得到的HTTP响应为交替出现8085和8084。这表明Ribbon客户端正在为轮询方式实现负载均衡。

还有一种更简便的方法,标注@RibbonClient并设置需要获取的服务名,并给RestTemplate标注上@LoadBalance注解。可以直接通过RestTemplate使用URL http://myprovider/ 进行请求,Ribbon同样有助于实现负载均衡。 aUTzvFAlx7qJnEbhuBhOc1TFdVP1f7B7DDDhSpA4yD84rdeutwdSjvnBuINAc9xx


@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
@Slf4j
@RestController
@RibbonClient(name = "myprovider")
public class EurekaClientApplication2 {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping(value = "/sayHello" ,method = RequestMethod.GET)
    public String sayHello(String name) {
        String result=restTemplate.getForObject("http://myprovider/sayHello?name= "+name,String.class);
        return  result;
    }
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication2.class, args);
    }
}

点击中间区域
呼出菜单
上一章
目录
下一章
×