说明:注册中心使用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方法 @RestControllerpublic 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() { //过滤器类型,取值:pre、route、post、error return "pre"; } @Override public int filterOrder() { //过滤器执行顺序,越小越优先执行 return 0; } @Override public boolean shouldFilter() { //过滤器执行条件 return true; } @Override public Object run() throws ZuulException { //过滤器执行逻辑 return "test"; }} 2.在SpringBoot启动类加入注解@EnableZuulProxy深入可阅读:Zuul网关源码解析