1.概述
在本文中,我們將介紹如何通過Zuul和Eureka一起使用來實現負載均衡。
我們將請求路由到註冊在Spring Cloud Eureka,並通過Zuul Proxy來發現的REST服務。
2.初始設置
我們需要設置Eureka服務器/客戶端,如文章介紹微服務中服務治理Spring-Cloud-Netflix-Eureka所示。
3.配置Zuul
Zuul還從Eureka服務站點獲取服務列表並進行服務器端負載平衡。
3.1Maven配置
首先,我們將爲我們的pom.xml添加Zuul Server和Eureka依賴項:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
3.2與Eureka整合
其次,我們將在Zuul的application.properties文件中添加必要的屬性:
server.port=8762
spring.application.name=zuul-server
eureka.instance.preferIpAddress=true
eureka.client.registerWithEureka=true
eureka.client.fetchRegistry=true
eureka.serviceurl.defaultzone=http://localhost:8761/eureka/
在這裏,我們告訴Zuul在Eureka註冊自己的服務,並在8762端口運行。
接下來,我們將使用@EnableZuulProxy和@EnableDiscoveryClient實現主類。使用@EnableZuulProxy將此指示爲Zuul Server,並且用@EnableDiscoveryClient將此指示爲Eureka客戶端:
@SpringBootApplication
@EnableZuulProxy
@EnableDiscoveryClient
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
我們將瀏覽器指向http://localhost:8762/routes。這應該顯示Eureka發現的Zuul可用的所有路線:
{"/spring-cloud-eureka-client/**":"spring-cloud-eureka-client"}
現在,我們將使用獲得的Zuul Proxy路由與Eureka客戶端進行通信。將我們的瀏覽器指向http://localhost:8762/spring-cloud-eureka-client/greeting應該生成如下響應:
Hello from 'SPRING-CLOUD-EUREKA-CLIENT with Port Number 8081'!
4.使用Zuul加載平衡
當Zuul收到請求時,它會獲取一個可用的物理位置,並將請求轉發給實際的服務實例。Zuul緩存服務實例的位置並將請求轉發到實際位置的整個過程是開箱即用的,不需要額外的配置。
在這裏,我們可以看到Zuul如何封裝同一服務的三個不同實例:
在內部,Zuul使用Netflix功能區從服務發現(Eureka Server)中查找服務的所有實例。讓我們在出現多個實例時觀察這種行爲。
4.1註冊多個實例
我們將從運行兩個實例(8081和8082端口)開始。
一旦所有實例都啓動,我們可以在日誌中觀察實例的物理位置在DynamicServerListLoadBalancer中註冊,並且路由映射到Zuul Controller,後者負責將請求轉發到實際實例:
17:23:36.983 [http-nio-8762-exec-4] INFO c.n.l.DynamicServerListLoadBalancer - DynamicServerListLoadBalancer for client
spring-cloud-eureka-client initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=spring-cloud-eureka-client,
current list of Servers=[192.168.8.234:8081, 192.168.8.234:8082],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;
Instance count:2; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;]
通過Eureka的控制檯,可以看到註冊後的服務實例。
4.2負載平衡示例
讓我們將瀏覽器導航到http://localhost:8762/spring-cloud-eureka-client/greeting。
刷新幾次。每一次,我們都應該看到略有不同的結果:
Hello from 'SPRING-CLOUD-EUREKA-CLIENT with Port Number 8081'!
Hello from 'SPRING-CLOUD-EUREKA-CLIENT with Port Number 8082'!
Hello from 'SPRING-CLOUD-EUREKA-CLIENT with Port Number 8081'!
Zuul收到的每個請求都以循環方式轉發給不同的實例。
5.結論
正如我們所見,Zuul爲Rest服務的所有實例提供了一個URL,並進行負載均衡以將請求以循環方式轉發到其中一個實例。
示例完整代碼