首先在使用前先将所需的jar导入:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
官方文档上说了,在使用zuul中,需要eureka-client就是客户端,而不用eureka-server。
然后在启动类加上@EnableZuulProxy注解,这个注解是包含了eureka所需的注解,所以只讲eureka的包导入就好了,eureka不用这个注解注册@EnableDiscoveryClient。
然后是配置文件中,该使用的配置:
server.port: 8064
eureka:
client:
serviceUrl:
defaultZone: http://localhost:80/eureka/
spring:
application:
name: spring-boot-gateway-zuul
zuul:
#ignoredServices: '*' #这里所谓的拒绝,是在通过zuul访问其他微服务的时,是不成功的,如果没有设置本属性,在通过本zuul访问其他微服务上的节点时可行的
routes:
eureka-ribbon: /test/** #这里的这个eureka-ribbon是灵活的,如果是要指定为另外一个微服务的spring.application.name 的值,那么就会变成RIBBON-CONSUMER-FILE-CONFIGURATION: /test/**
配置代理路径时有两种方式:
#第一种
zuul:
routes:
users: #这里的users只要是唯一的就可以,但是第二种的就不能乱取。
path: /myusers/**
serviceId: users_service
#第二种
zuul:
routes:
users: /myusers/**
#第三种 有负载均衡功能,但是要关闭ribbon对eureka的支持,有疑问请看官方文档
zuul:
routes:
user:
path: /test/**
serviceId: eureka-ribbon
ribbon:
eureka:
enabled: false
eureka-ribbon: #这里是ribbon用的serviceId切记
ribbon:
listOfServers: http://localhost:8090,http://localhost:8091
然后启动服务后得到结果:
会看到zuul已经注册上去了,使用http://localhost:8064/test/index能得到如下结果:
在配置文件中eureka-ribbon: /test/**后面的值是用于在请求时必须加上的一个前缀如官方文档说的:
前面说了,当zuul配置了:
zuul:
#ignoredServices: '*'
使用spring.application.name的值加对应的log-user-instance节点时是访问失败的
http://localhost:8064/ribbon-consumer-file-configuration/log-user-instance
因为zuul默认是对所有项目都能访问,只要是注册在了eureka上面的项目。
zuul在访问的时候要小心,有些小问题,比如大小写问题:
http://localhost:8064/ribbon-consumer-file-configuration/log-user-instance这样是能访问成功的。
http://localhost:8064/RIBBON-CONSUMER-FILE-CONFIGURATION/log-user-instance这样是失败的。
有时候为了偷懒直接在eureka中复制的application值全为大写,在zuul中用不了。
如有问题请参考官方文档。