目录
一、Service Discovery
1、Netflix Eureka
二、Load Balancing
1、blocking ribbon
2、reactive loadbalancer
三、例子
1、TestServer
2、ServerRegistry
3、GatewayServer
Spring Cloud Gateway若需要接入ServiceRegistry中的服务信息,并将接收到的请求正确的转发到这些服务对应的后端的服务器中,就需要配置如下两个组件:
- Service Discovery # 从ServiceRegistry获取服务及服务对应的可访问服务器信息
- Load Balancing # 根据配置的负载规则,从服务对应的可访问服务器中选取一个,将请求转发到这个服务器
Spring Cloud对这两种组件提供了抽象API,可以在spring-cloud-commons中找到。接口分别为:
org.springframework.cloud.client.discovery.DiscoveryClient
org.springframework.cloud.client.loadbalancer.LoadBalancerClient
Spring Cloud Gateway的基础配置如下:
Maven配置
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-webflux
org.springframework.cloud
spring-cloud-starter
${spring-cloud.version}
org.springframework.cloud
spring-cloud-starter-gateway
${spring-cloud.version}
application.properties配置
# 此参数默认为true,因此可以不设置
spring.cloud.gateway.enabled=true
以上两种组件,有多种第三方组件提供了这些功能,Spring Cloud对这些组件提供了相应的封装。下面分别介绍如何配置这两个组件。
Spring Cloud支持的组件为:
- Netflix Eureka
- Consul
- Zookeeper
下面以Netflix Eureka为例,介绍一下如何配置
Maven配置
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
${spring-cloud.version}
application.properties配置
spring.cloud.discovery.enabled=true
spring.cloud.service-registry.auto-registration.enabled=falseeureka.client.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
# eureka.instance.hostname=localhost
# eureka.instance.metadataMap.zone=
配置是从如下类中初始化的:
org.springframework.cloud.gateway.discovery.GatewayDiscoveryClientAutoConfiguration
其中会加载:
org.springframework.cloud.netflix.eureka.reactive.EurekaReactiveDiscoveryClient
默认情况下,Spring Cloud Gateway使用的配置等同于如下内容,它们是写在代码中的,这个默认配置一般就可以满足使用要求了,不需要再对它进行配置:
spring.cloud.gateway.discovery.locator.predicates[0].name: Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+serviceId+'/**'"
spring.cloud.gateway.discovery.locator.predicates[1].name: Host
spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]: "'**.foo.com'"
spring.cloud.gateway.discovery.locator.filters[0].name: Hystrix
spring.cloud.gateway.discovery.locator.filters[0].args[name]: serviceId
spring.cloud.gateway.discovery.locator.filters[1].name: RewritePath
spring.cloud.gateway.discovery.locator.filters[1].args[regexp]: "'/' + serviceId + '/(?.*)'"
spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remaining}'"
其中,"'/'+serviceId+'/**'"会被SpEL解析,SpEL会将serviceId替换成请求URL中的实际serviceId。
如果特殊需要,也可能改变以上配置,比如要针对TestServer服务,可以这样配置:
spring.cloud.gateway.discovery.locator.predicates[0].name=Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]="/TestServer/**"
spring.cloud.gateway.discovery.locator.predicates[1].name=Host
spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]="**"
spring.cloud.gateway.discovery.locator.filters[0].name=RewritePath
spring.cloud.gateway.discovery.locator.filters[0].args[regexp]="/TestServer/(?.*)"
spring.cloud.gateway.discovery.locator.filters[0].args[replacement]="/${remaining}"
比如接收到如下请求:
http://www.test.com/TestServer/info.jsp
Spring Cloud Gateway会将此请求转发到如下地址:
http://IP:port/info.jsp
IP:port是部署TestServer服务的服务器的ip和port
Spring Cloud Gateway接收到请求后,从把请求URL转化为如下形式交由LoadBalancerClient处理,比如:
http://www.test.com/TestServer/info.jsp
会转化为:
lb://TestServer/info.jsp
然后将由LoadBalancerClient处理。
Spring Cloud Gateway当前支持两种组件:
- blocking ribbon
- reactive loadbalancer
application.properties配置
spring.cloud.loadbalancer.ribbon.enabled=true #此为默认配置
此配置会使用org.springframework.cloud.gateway.filter.LoadBalancerClientFilter,它由org.springframework.cloud.gateway.config.GatewayLoadBalancerClientAutoConfiguration 初始化。
使用此配置后,需要使用Netflix Ribbon组件,因此要添加依赖。
Maven配置
org.springframework.cloud
spring-cloud-starter-netflix-ribbon
${spring-cloud.version}
与ribbon的相关配置ribbonPing和ribbonServerList,会在org.springframework.cloud.netflix.ribbon.eureka.EurekaRibbonClientConfiguration中初始化:
ribbonPing:
com.netflix.niws.loadbalancer.NIWSDiscoveryPing #将由Eureka来决定服务器是否正常
ribbonServerList:
org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList #从Eureka client中获取服务器列表
它是对com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList的扩展,DiscoveryEnabledNIWSServerList将从Eureka client中获取服务器列表
其它与ribbon的相关配置,仍会使用org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration初始化。
ribbon中一些重要类的功能说明:
- ZonePreferenceServerListFilter 只会使用指定区域内的服务器
- ZoneAffinityServerListFilter 优先使用指定区域内的服务器,若指定区域内无服务器可用,则选择一个别的区域内的服务器。
- ZoneAvoidanceRule
- ZoneAvoidancePredicate 当一个zone的度量统计值超过一个阈值时,这个zone下的所有server将被过滤掉
- AvailabilityPredicate 过滤掉已熔断的server,和并发连接数据过大的server
- ZoneAwareLoadBalancer 针对不同的zone创建不同的LoadBalancer实例来进行处理
application.properties配置
spring.cloud.loadbalancer.ribbon.enabled=false #此为官方文档推荐配置
此配置会使用org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter,它由org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration 初始化。
此配置只会用到Spring Cloud自己的实现。
Maven配置
org.springframework.cloud
spring-cloud-starter-loadbalancer
${spring-cloud.version}
其中使用的LoadBalancer:org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer
Maven
UTF-8
2.2.1.RELEASE
org.springframework.boot
spring-boot-starter-parent
2.2.1.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
${springCloud.version}
org.springframework.cloud
spring-cloud-netflix-ribbon
bootstrap.properties
server.port=8081
spring.application.name=TestServer
spring.cloud.discovery.enabled=true
spring.cloud.service-registry.auto-registration.enabled=true
application.properties
eureka.client.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/eureka.client.register-with-eureka=true
# hostname为此实例提供给外部调用的域名
eureka.client.fetch-registry=trueeureka.instance.hostname=localhost
Java
package com.test.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@EnableDiscoveryClient
@SpringBootApplication(exclude = { TaskSchedulingAutoConfiguration.class, ErrorMvcAutoConfiguration.class })
@RestController
public class AppBoot {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(AppBoot.class, args);
ctx.registerShutdownHook();
}
@RequestMapping("/home")
public String home() {
String home ="home:server1:" + System.currentTimeMillis();
System.out.print(home);
return home;
}
@RequestMapping("/info")
public String info() {
String info ="info:server1:" + System.currentTimeMillis();
System.out.print(info);
return info;
}
}
可以多配置一些server,只要server.port不重复就行。
application.properties
server.port=8761
spring.application.name=ServiceRegistryServer
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=falseeureka.instance.hostname=localhost
Maven
UTF-8
2.2.1.RELEASE
org.springframework.boot
spring-boot-starter-parent
2.2.1.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter
${spring-cloud.version}
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
${spring-cloud.version}
Java
package com.test.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class ServiceRegistryEurekaApp {
public static void main(String[] args) throws Exception {
SpringApplication.run(ServiceRegistryEurekaApp.class, args);
}
}
application.properties
server.port=8070
spring.application.name=gatewayServer
spring.cloud.discovery.enabled=true
spring.cloud.service-registry.auto-registration.enabled=falseeureka.client.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
eureka.instance.hostname=localhost
spring.cloud.loadbalancer.ribbon.enabled=true
# unit: ms
spring.cloud.gateway.httpclient.connect-timeout=10000
spring.cloud.gateway.httpclient.response-timeout=5s
Maven
UTF-8
UTF-8
1.8
2.2.1.RELEASE
org.springframework.boot
spring-boot-starter-parent
2.2.1.RELEASE
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-webflux
org.springframework.cloud
spring-cloud-starter
${spring-cloud.version}
org.springframework.cloud
spring-cloud-starter-gateway
${spring-cloud.version}
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
${spring-cloud.version}
org.springframework.cloud
spring-cloud-starter-netflix-ribbon
${spring-cloud.version}
Java
package com.test.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
@Configuration
@SpringBootApplication
@EnableDiscoveryClient
public class AppBoot {
public static void main(String[] args) {
SpringApplication.run(AppBoot.class, args);
}
}
通过访问:http://localhost:8070/TestServer/info,就可以看到返回的结果了。
参考文档
Spring Cloud Gateway
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.2.RELEASE/reference/html
Spring Cloud Netflix
https://cloud.spring.io/spring-cloud-static/spring-cloud-netflix/2.2.2.RELEASE/reference/html
Spring Cloud Commons
https://cloud.spring.io/spring-cloud-static/spring-cloud-commons/2.2.2.RELEASE/reference/html