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

SpringCloud-Zuul实现路由和服务过滤

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

一、maven配置

 <groupId>com.wk.sc</groupId>
    <artifactId>springcloud-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

二、application.yml配置

server:
  port: 8769
spring:
  application:
    name: service-zuul
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
# 配置路由策略
zuul:
  routes:
    api-a:
      path: /api-a/**   # 路由规则
      serviceId: service-ribbon  # 匹配服务
    api-b:
      path: /api-b/**
      serviceId: service-feign

三、启动类

@EnableZuulProxy //开启路由代理
@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceZuulApplication.class, args);
    }

}

四、路由测试

http://localhost:8769/api-a/hi?name=zhangsan
http://localhost:8769/api-b/hi?name=zhangsan

根据路由策略配置请求不同的服务

五、过滤实现

/**
 * 自定义zuul过滤规则
 *
 */
@Component
public class MyFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(MyFilter.class);

    /**
     * 定义过滤周期类型
     * 在zuul中定义了4中过滤周期类型:
     * pre:路由前
     * routing:路由时
     * post:路由后
     * error:发生错误时调用
     *
     * @return
     */
    @Override
    public String filterType() {

        return "pre";
    }

    /**
     * 过滤顺序
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 根据条件定义是否需要过滤:
     * true:需要过滤
     * false:不需要
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //需要过滤生效,此处需要返回true
        return true;
    }

    /**
     * 过滤器具体实现,可以结合业务需求进行复杂的实现
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        logger.info("请求信息,方法[{}],URL[{}]", request.getMethod(), request.getRequestURL().toString());
        //模拟token校验
        String token = request.getParameter("token");
        if (token == null || token.length() == 0){
            //token校验失败返回401
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            try {
                requestContext.getResponse().getWriter().write("token 为空");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            logger.info("校验通过");
        }
        return null;
    }
}


六、过滤测试

http://localhost:8769/api-a/hi?name=zhangsan&token=uuid-123

分别带token和不带token请求查看效果

转载于:https://www.jianshu.com/p/561a2e48e0e9