欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

06 使用zuul进行路由和过滤

程序员文章站 2022-07-12 18:52:41
...

使用zuul可以对微服务提供的api进行路由和保护。本节将阐述zuul在微服务中的两种用法:路由和过滤。

1、环境约束

  • win10 64为操作系统
  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64

2、前提约束

3、操作步骤

3.1 路由

  • 创建一个springcloud项目,包括springweb、eureka client、zuul模块,关键依赖如下:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>

注意:springboot的版本是2.1.8.RELEASE,springcloud的版本是Greenwich.SR2

  • 修改application.properties,内容如下:
server.port=8003
eureka.client.service-url.defaultZone=http://localhost:7561/eureka
spring.application.name=zuul-service
zuul.routes.traditional-url.path=/api/url/**
zuul.routes.traditional-url.url=http://localhost:8001
zuul.routes.orient-service-url.path=/api/service/**
zuul.routes.orient-service-url.service-id=provider-service
zuul.prefix=/wanho
  • 在主启动类上除@SpringBootApplication之外,加入以**解:
@EnableEurekaClient
@EnableZuulProxy

3.2 过滤

  • 以完成3.1操作为基础,在主启动类的同级目录下加入PasswordFilter.java
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class PasswordFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "post"; // 请求处理完成后执行的filter
    }

    @Override
    public int filterOrder() {
        return 1; // 优先级为0,数字越大,优先级越低
    }

    @Override
    public boolean shouldFilter() {
        boolean enable = true;//为true一定会执行run
        return enable;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String password= request.getParameter("password");
        if(StringUtils.isEmpty(password) || !password.equalsIgnoreCase("123456")){
            //不放行
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(500);
            ctx.setResponseBody("password is empty");
            return null;
        }else{
            //放行
            ctx.setSendZuulResponse(true);
            ctx.setResponseStatusCode(200);
            return null;
        }
    }
}