Hello你们好,我是初晨,本章咱们学习SpringCloud 服务网关Zuul的使用。你们有问题和意见能够发邮箱mr_beany@163.com
Zuul是Spring Cloud服务系列中的微服务API网关。java
Zuul的核心是一系列的filters, 其做用能够类比Servlet框架的Filter,或者AOP。
git
全部的请求都会通过Zuul的验证以后到达其余各个服务。做为一个边界性质的应用程序,Zuul提供了动态路由、监控、弹性负载和安全功能。Zuul底层利用各类filter实现以下功能:web
1:建立过程与 SpringCloud 实战二:Client的建立和高可用 同样
spring
2:打开pom文件,添加依赖bootstrap
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>复制代码
3:修改启动类,添加@EnableZuulProxy后端
4:修改配置文件名称为bootstrap.ymlapi
spring:
application:
name: api-gateway
cloud:
config:
discovery:
enabled: true
service-id: CONFIG
profile: dev复制代码
5:打开git仓库,建立配置文件安全
6:启动服务,访问http://localhost:8761/
bash
能够看到网关服务已经注册成功。app
7:经过网关服务的路由来访问其余服务接口
咱们来访问前面为建立组件间通讯建立的http://localhost:8081/getServerResult
能够访问,再经过网关访问http://localhost:8085/client/getServerResult
其中8085是服务网关的ip,client表明着client服务,getServerResult表明访问路径
8:自定义路由
经过Zuul每次访问client服务时都须要带上client,那么怎么才能不使用client而使用自定义的名称呢?
修改api-gateway服务配置文件,添加以下配置
zuul:
routes:
myClient:
path: /myClient/**
serviceId: client复制代码
这时地址栏中输入http://localhost:8085/myClient/getServerResult
仍然能够获取到返回结果。
那么咱们怎么查看全部路由的规则呢?
地址栏中输入http://localhost:8085/actuator/routes
9:禁用路由
修改api-gateway配置文件,添加以下
zuul:
ignored-patterns:
- /**/getServerResult复制代码
此时咱们git上的配置文件应该为
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
management:
endpoints:
web:
exposure:
include: '*'
zuul:
routes:
myClient:
path: /myClient/**
serviceId: client
# 设置能够传递请求头
sensitiveHeaders:
ignored-patterns:
- /**/getServerResult复制代码
这里咱们把这个url给禁用掉,再次访问该地址
10:动态配置路由
利用咱们上篇文章讲的统一配置中心,来实现动态配置路由功能,你们能够先回想一下配置的步骤
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>复制代码
spring:
rabbitmq:
host: 192.168.99.100
username: user
password: password
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
management:
endpoints:
web:
exposure:
include: '*'
zuul:
routes:
myClient:
path: /myClient/**
serviceId: client
# 设置能够传递请求头
sensitiveHeaders:
ignored-patterns:
- /**/getServerResult复制代码
package com.example.apigateway;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
@Component
public class ZuulConfig {
@ConfigurationProperties("zuul")
@RefreshScope
public ZuulProperties zuulProperties(){
return new ZuulProperties();
}
}复制代码
注意这时咱们访问http://localhost:8085/myClient/getServerResult
是404的,由于咱们已经在配置文件中把url禁用了
修改git上api-gateway的配置文件,把禁用http://localhost:8085/myClient/getServerResult
的配置注释掉
而后postman访问http://localhost:8084/actuator/bus-refresh
来刷新配置文件
再次访问