首先准备两个用户微服务,端口分别是8889,与8888,在eureka的server端,如下
微服务的配置文件,如下:
server.port=8889
spring.application.name=spring-cloud-user
spring.jpa.generate-ddl=false
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.datasource.platform=h2
spring.datasource.schema=classpath:schema.sql
spring.datasource.data=classpath:data.sql
logging.level.root=info
logging.level.org.org.hibernate=info
logging.level.com.com.chukun=debug
eureka.client.serviceUrl.defaultZone=http://chukun:123456@localhost:8761/eureka/
这里做特别说明,这里必须注释起来,不然别的服务请求不到,会报错误
##eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.application.name}:${spring.application.instance_id:${server.port}}
如果写了eureka.instance.prefer-ip-address=true,另一个微服务以vip的方式请求用户微服务会报如下错误:
服务请求端配置:
server.port=8887
spring.application.name=spring-cloud-movie
logging.level.root=info
logging.level.org.org.hibernate=info
logging.level.com.com.chukun=debug
eureka.client.serviceUrl.defaultZone=http://chukun:123456@localhost:8761/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.application.name}:${spring.application.instance_id:${server.port}}
在服务启动的入口函数的RestTemplate上添加@LoadBalanced即可
请求处理类:
@Resource
private RestTemplate restTemplate;
@GetMapping("/movie/{id}")
public User findUserById(@PathVariable long id) {
//这里写服务提供方的vip,也就是服务的名称
//spring.application.name=spring-cloud-user
return this.restTemplate.getForObject("http://spring-cloud-user/user/"+id, User.class);
}
至此,就可以实现客户端的负载均衡了,结果如下:
利用ribbon实现客户端的负载均衡了。