上篇文章我们成功的将providr和consumer注册到eureka上面了。但是有两个问题:
1、 consumer通过rest请求provider的时候,url是硬编码
return this.restTemplate.getForEntity("http://localhost:8001/simple/" + id, User.class).getBody();
2、 provider怎么做到负载均衡。
解决硬编码问题
上篇文章结尾我们能看到provider在启动并注册到eureka后,eureka会有一行log
- Registered instance MICIROSERVICE-PROVIDER/windows10.microdone.cn:miciroservice-provider:8001 with status UP (replication=false)
这里的miciroservice-provider是我们定义在provider application.yml里的spring.application.name,这里也代表VIP(虚拟ip),也就是consumer可以通过这个IP去访问provider的应用例如:http://miciroservice-provider/simple/2 == http://localhost:8001/simple/2
所以我们只需要将上面的访问url改成对应的虚拟IP就可以了。
return this.restTemplate.getForEntity("http://miciroservice-provider/simple/" + id, User.class).getBody()
负载均衡
本篇文章使用ribbon实现负载均衡,很简单,一句话。
package com.zhuyang.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
public class DemoMicroserviceConsumerUserApplication {
@Bean
@LoadBalanced //ribbon
public RestTemplate restTemplate() { // equals to RestTemplate restTemplate = new RestTemplate()
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(DemoMicroserviceConsumerUserApplication.class, args);
}
}
为了测试,我们可以启动两个provider实例(注意:port不一样),然后多次访问consumer,正常情况下两个provider应该都会命中到,而且次数应该一样,因为默认是轮询的方式。