一 创建一个Maven工程,建立项目microservice-gateway-zuul,并为项目填写如下依赖。
<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>
二 在启动类上添加注解@EnableZuulProxy,声明一个Zuul代理。该代理使用Ribbon来定位注册在Eureka Server中的微服务;同时,该代理还整合了Hystrix,从而实现了容错,所有经过Zuul的请求都会在Hystrix命令中执行。
package com.itmuch.cloud.study;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
三 编写配置文件application.yml
server:
port: 8040
spring:
application:
name: microservice-gateway-zuul
eureka:
client:
service-url:
defaultZone:http://localhost:8761/eureka/
instance:
prefer-ip-address: true
四 路由测试
1 启动eureka
2 启动user微服务
3 启动movie微服务
4 启动zuul
说明默认情况下,Zuul会代理所有注册到Eureka Server的微服务,并且Zuul的路由规则如下:
http://ZUUL_HOST:ZUUL_POTT/微服务在Eureka上的serviceID/**会被转发到serviceId对应的微服务。
五 负载均衡测试
1 启动eureka
2 启动多个user实例
3 启动项目zuul,此时Eureka Server首页如下:
4 多次访问
http://localhost:8040/microservice-provider-user/1,会发现两个用户微服务节点都会打印类似以下的日志:
Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.balance as balance3_0_0_, user0_.name as name4_0_0_, user0_.username as username5_0_0_ from user user0_ where user0_.id=?
说明Zuul可以使用Ribbon达到负载均衡的效果。
六 Hystrix容错与监控
1 启动eureka
2 启动user用户微服务
3 启动电影微服务
4 启动zuul
5 启动项目Dashboard
7 Hystrix Dashboard中输入http://localhost:8040/hystrix.stream,随意指定一个Title,并点击Monitor Stream按钮后,结果如下: