目录
1、在start.spring.io中,添加Web、Actuator、Eureka Client、Ribbon模块
1)、在启动类中添加@EnableEurekaClient将服务注册到之前创建的Eureka Server注册中心
4)、使用Spring Profiles分别启动三个服务(端口分别为8765、8766、8767)
1)、将RestTemplate注册成一个Bean,并使用@LoadBalanced进行修饰
3、在项目中创建ribbon-consumer-eureka模块
1)、在启动类中添加@EnableEurekaClient将服务注册到注册中心,并添加@RibbonClient添加服务调用端的配置
2)、将RestTemplate注册成一个Bean,并使用@LoadBalanced进行修饰
1、No instances available for ribbon-user-provider
在Spring Cloud-Eureka Server集群和客户端调用之后,我们知道了Eureka服务器是怎么实现的,以及一个实例服务怎么注册到注册中心。当然生产环境中每个应用都是多节点(集群)注册到注解中心,并根据一定的负载均衡机制对服务进行调用。负载均衡的实现大致为分两类:
1、集中式
如硬件的F5和软件的Nginx,中间增加一层代理。
2、进程内
当客户端从注册中心获取到服务提供段的服务列表后,在客户端自行路由计算,直接对服务端进行调用。而Ribbon就属于这种。Ribbon负载均衡实现项目的地址为: https://github.com/kevin-lihongmin/spring-cloud-project-kevin/tree/master/ribbon-demo
当前demo中有三个maven模块,分别为:
ribbon-provider:以Spring Profiles的方式启动三个服务注册到注册中心
ribbon-consumer:服务不注册到注册中心,使用本地配置服务提供者列表的方式,在本地进行负载均衡
ribbon-consumer-eureka:服务注册到注册中心,根据客户端配置的服务调用方的名称,从注册中心获取服务列表地址,在客户端进行负载均衡
一、两种模式的Ribbon负载均衡搭建
1、在start.spring.io中,添加Web、Actuator、Eureka Client、Ribbon模块
2、在项目中创建ribbon-provider模块
1)、在启动类中添加@EnableEurekaClient将服务注册到之前创建的Eureka Server注册中心
为了方便直接在启动类中添加@RestController,并提供接口服务,如下:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableEurekaClient
@SpringBootApplication
public class UserRibbonProviderApplication {
@Value("${server.port}")
private String port;
@GetMapping("user/{id}")
public String getUserById(@PathVariable String id) {
User user = new User();
user.setId(Long.parseLong(id));
user.setName("userName" + id);
System.out.println("send to server !");
return user.toString() + "( server.port = " + port + ")";
}
public static void main(String[] args) {
SpringApplication.run(UserRibbonProviderApplication.class, args);
}
}
3)、配置文件
与Eureka Server注册中心一样,copy多个Profiles的application.properties的配置文件,
需要注意:
spring.application.name: 服务者的引用名称必须相同,则组为一组服务
eureka.client.serviceUrl.defaultZone:将服务注册到同一注册中心
eureka.instance.instance-id:注册中心的服务id
配置信息如下:
# Eureka 注册中心服务器端口 eureka.server.port = 9091 # 当前服务端口 server.port=8765 spring.application.name=ribbon-user-provider # 开启Eureka客户端的健康检查 eureka.client.healthcheck.enabled=true # 指定客户端对应的注册中心服务器的地址, 只需要注册到其中的一个注册中心即可 eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka/,\ http://localhost:8760/eureka/,http://localhost:8759/eureka/ # 表示注册到注册中心的是IP eureka.instance.prefer-ip-address=true # 册中心实例的表示注册到注ID规则 eureka.instance.instance-id=${spring.application.name}:\ ${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}} # 表示续约更新时间间隔,也就是客户端健康检查的心跳时间间隔 eureka.instance.lease-renewal-interval-in-seconds=5
## Eureka 注册中心服务器端口 eureka.server.port = 9092 # 当前服务端口 server.port=8766 spring.application.name=ribbon-user-provider # 开启Eureka客户端的健康检查 eureka.client.healthcheck.enabled=true # 指定客户端对应的注册中心服务器的地址, 只需要注册到其中的一个注册中心即可 eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka/,\ http://localhost:8760/eureka/,http://localhost:8759/eureka/ # 表示注册到注册中心的是IP eureka.instance.prefer-ip-address=true # 册中心实例的表示注册到注ID规则 eureka.instance.instance-id=${spring.application.name}:\ ${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}} # 表示续约更新时间间隔,也就是客户端健康检查的心跳时间间隔 eureka.instance.lease-renewal-interval-in-seconds=5
# Eureka 注册中心服务器端口 eureka.server.port = 9093 # 当前服务端口 server.port=8767 spring.application.name=ribbon-user-provider # 开启Eureka客户端的健康检查 eureka.client.healthcheck.enabled=true # 指定客户端对应的注册中心服务器的地址, 只需要注册到其中的一个注册中心即可 eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka/,\ http://localhost:8760/eureka/,http://localhost:8759/eureka/ # 表示注册到注册中心的是IP eureka.instance.prefer-ip-address=true # 册中心实例的表示注册到注ID规则 eureka.instance.instance-id=${spring.application.name}:\ ${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}} # 表示续约更新时间间隔,也就是客户端健康检查的心跳时间间隔 eureka.instance.lease-renewal-interval-in-seconds=5
4)、使用Spring Profiles分别启动三个服务(端口分别为8765、8766、8767)
查看注册中心的服务,如下:
3、在项目中创建ribbon-consumer模块
1)、将RestTemplate注册成一个Bean,并使用@LoadBalanced进行修饰
ribbon在客户端实现路由,就是依靠RestTemplate的拦截器实现的,后续专门讲解,启动类如下:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class UserRibbonConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(UserRibbonConsumerApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
}
2)、添加一个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;
@RestController
public class UserRibbonController {
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServicePath}")
private String userServicePath;
@GetMapping("/getRemoteUser/{userId}")
public String getRemoteUser(@PathVariable Long userId) {
return restTemplate.getForObject(userServicePath + userId, String.class);
}
}
3)、配置文件
需要注意:
ribbon-user-provider.ribbon.listOfServers中是ribbon-user-provider 和 user.userServicePath中的ribbon-user-provider是对应的,原理将在下以章中讲解,并且一点添加配置,否则会报:
# 不注册到注册中心
ribbon.eureka.enabled=false
server.port = 8768 spring.application.name = ribbon-user-consumer eureka.client.healthcheck.enabled = true # 不注册到注册中心 ribbon.eureka.enabled=false # 服务提供者的列表 其中:providers是自定义的,ribbon 和 listOfServers是spring cloud定义的 ribbon-user-provider.ribbon.listOfServers = localhost:8765,localhost:8766,localhost:8767 # 路由规则 # ribbon-user-provider.ribbon.NFLoadBalancerRuleClassName = com.netflix.loadbalancer.RandomRule user.userServicePath = http://ribbon-user-provider/user/ ## Management 安全失效 # management.security.enabled = false spring.cloud.loadbalancer.retry.enabled = true ## Eureka 客户端应用实例状态 URL eureka.instance.statusPageUrlPath = /health
4)、启动服务,查看效果
在浏览器输入 http://localhost:8768/getRemoteUser/1,则可以获取到路由到3个服务器端的结果(端口会交替变更):
User{id=1, name='userName1'}( server.port = 8766)
3、在项目中创建ribbon-consumer-eureka模块
1)、在启动类中添加@EnableEurekaClient将服务注册到注册中心,并添加@RibbonClient添加服务调用端的配置
2)、将RestTemplate注册成一个Bean,并使用@LoadBalanced进行修饰
ribbon在客户端实现路由,就是依靠RestTemplate的拦截器实现的,后续专门讲解,启动类如下:
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.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* 使用Eureka 注册中心,根据服务提供者的注册名称,获取服务配置列表,再在客户端进行负载均衡
*
*/
@EnableEurekaClient
@SpringBootApplication
@RibbonClients({@RibbonClient(name = "ribbon-user-provider")})
public class UserRibbonEurekaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(UserRibbonEurekaConsumerApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
}
3)、也添加一个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;
@RestController
public class UserRibbonController {
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServicePath}")
private String userServicePath;
@GetMapping("/getRemoteUser/{userId}")
public String getRemoteUser(@PathVariable Long userId) {
return restTemplate.getForObject(userServicePath + userId, String.class);
}
}
4)、配置文件
需要注意:
不能配置 ribbon.eureka.enabled 和 ribbon-user-provider.ribbon.listOfServers
# Eureka注册中心的地址
eureka.client.serviceUrl.defaultZone = http://127.0.0.1:8761/eureka/,\
http://localhost:8760/eureka/,http://localhost:8759/eureka/
server.port = 8769
spring.application.name = ribbon-user-consumer-eureka
eureka.client.healthcheck.enabled = true
# 路由规则
# ribbon-user-provider.ribbon.NFLoadBalancerRuleClassName = com.netflix.loadbalancer.RandomRule
user.userServicePath = http://ribbon-user-provider/user/
## Management 安全失效
# management.security.enabled = false
spring.cloud.loadbalancer.retry.enabled = true
## Eureka 客户端应用实例状态 URL
eureka.instance.statusPageUrlPath = /health
5)、启动服务,查看效果
在浏览器输入 http://localhost:8769/getRemoteUser/1,则可以获取到路由到3个服务器端的结果(端口会交替变更):
User{id=1, name='userName1'}( server.port = 8766)
二、搭建过程中遇到的问题
1、No instances available for ribbon-user-provider
在搭建ribbon-consumer的时候,即客户端没有注册到注册中心,使用本地的服务listOfServers 列表进行负载均衡。没有配置 ribbon.eureka.enabled=false 则会报该错。
2、I/O error on GET request for "http://ribbon-user-provider/user/1": ribbon-user-provider; nested exception is java.net.UnknownHostException: ribbon-user-provider
在搭建ribbon-consumer的时候,没有在注入RestTemplate实例的时候添加@LoadBalanced注解,则会报该错,应该:
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}