前面文章中已经将服务注册到了Eureka,但是还没有解决请求地址硬编码和负载均衡的问题。
这边文章,我们讲述使用Ribbon完成请求以及负载均衡。让电影微服务调用用户微服务的时候,解决请求地址和端口的硬编码
实现负载均衡
1.服务器端负载均衡:使用Nginx,由Nginx完成反向代理,实现负载均衡。
2.客户端负载均衡:电影微服务中有某个组件(Ribbon),可以知道有多少个可用的用户微服务的IP和端口,在组件中完成负载均衡算法。
Ribbon实现客户端负载均衡。
http://cloud.spring.io/spring-cloud-static/Camden.SR7/#netflix-ribbon-starter
Client Side Load Balancer: Ribbon
Ribbon 工作分为2步:
1.选择Eureka Server,优先选择在同一Zone且负载较少的Server.
2.根据用户指定的策略,在从Server取到的服务注册列表中选择一个地址。
策略包括:轮询,随机,响应时间加权。
1.加入依赖
在Spring-cloud-start-Eureka的依赖中已经依赖了spring-cloud-starter-ribbon.所以不用添加依赖
2.使用注解@LoadBalanced
代码实现:
只需要修改电影微服务即可。
我们通过拷贝,修改前面代码的电影微服务。重新创建了一个电影微服务:microservice-comsumer-movie-ribbon
1.主要是在RestTemplate上加入了@LoadBalanced,让restTemplate具备Ribbon负载均衡的能力。
启动类:
package com.dynamic.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient
public class ComsumerMovieRibbonApplication {
@Bean
@LoadBalanced//让restTemplate具备Ribbon负载均衡的能力。
public RestTemplate restTemplate()
{
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ComsumerMovieRibbonApplication.class, args);
}
}
2.修改MovieController中的用户微服务地址,修改硬编码为Eureka上注册的服务的ServicId,即用户微服务的application.name;
package com.dynamic.cloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.dynamic.cloud.entity.User;
@RestController
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id)
{
//http://localhost:7900/simple/
//VIP Virtual IP:虚拟IP,使用的是服务提供者的ServiceId,也就是application.name
//HAProxy HeartBeat
//microservice-provider-user:7900
return this.restTemplate.getForObject("http://microservice-provider-user/simple/"+id, User.class);
}
}
3.application.yml
server:
port: 7902
spring:
application:
name: microservice-comsumer-movie-ribbon
eureka:
client:
serviceUrl:
defaultZone: http://user:pass123@localhost:8761/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
启动Eureka,电影微服务,2个用户微服务。
实现了客户端负载均衡。