Zuul网关使用步骤
1.引入依赖父项目SpringCloud管理
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR12</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
2.导入网关微服务Zuul以及Eureka。
说明:注册中心使用Eureka,若使用其他注册中心,则引入相应的注册中心依赖。
<dependencies> <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> </dependencies>
3.在SpringBoot添加启动类@EnableZuulProxy
4.在ymp路由信息配置在文件中
以服务名称为goods示例:
zuul: routes: goods: path: /goods/** sensitiveHeaders: Authorization url: http://localhost:8081 prefix: /api addProxyHeaders: false
更多配置请阅读官网文档:https://docs.spring.io/spring-cloud-netflix/docs/2.2.9.RELEASE/reference/html/#router-and-filter-zuul
5.在goods添加微服务/添加微服务/添加微服务/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/添加/hello方法
@RestController public class GoodsController {
@GetMapping("/hello") public String hello() throws Exception{
return "hello world"; } }
6.直接调用网关服务
http://网关IP:网关端口/api/hello
使用网关过滤器的步骤
1.新建继承ZuulFilter并实现相应的方法。
@Component //必须放入Spring容器 public class AuthorizationFilter extends ZuulFilter {
@Override public String filterType() {
//过滤器执行顺序,越小越优先执行
return 0;
}
@Override
public boolean shouldFilter() {
//过滤器执行条件
return true;
}
@Override
public Object run() throws ZuulException {
//过滤器执行逻辑
return "test";
}
}
2.在SpringBoot启动类加入注解@EnableZuulProxy
深入可阅读:Zuul网关源码解析