前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringCloud 2.x学习笔记:4、Zuul(Greenwich版本)

SpringCloud 2.x学习笔记:4、Zuul(Greenwich版本)

作者头像
程裕强
发布2019-07-02 10:38:44
8320
发布2019-07-02 10:38:44
举报

版权声明:本文为博主原创文章,欢迎转载。 https://cloud.tencent.com/developer/article/1454223

1、Zuul简介

zuul 是netflix开源的一个API Gateway 服务器, 本质上是一个web servlet应用。

请参考官方文档:

https://springcloud.cc/spring-cloud-dalston.html#_router_and_filter_zuul

Zuul的主要功能是路由转发过滤器。路由功能是微服务的一部分,比如/api/user转发到到user服务,/api/shop转发到到shop服务。zuul默认和Ribbon结合实现了负载均衡的功能。

2、新建模块

2.1 pom文件
代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cntaiping.tpa</groupId>
    <artifactId>zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>zuul</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.cntaiping.tpa</groupId>
        <artifactId>cloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <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>
    </dependencies>
</project>
2.2 application.properties
代码语言:javascript
复制
eureka.client.serviceUrl.defaultZone=http://localhost:8800/eureka/
server.port=8400
spring.application.name=service-zuul
#表示只要访问以/api-a/开头的多层目录都可以路由到 id为compute-service的服务上
zuul.routes.consumer-feign=/api-a/**
zuul.routes.consumer-hystrix=/api-b/**

服务消费者也可以作为服务提供者。

以/api-a/ 开头的请求都转发给consumer-feign服务;以/api-b/开头的请求都转发给consumer-hystrix服务;

2.3 Application类
代码语言:javascript
复制
package com.cntaiping.tpa.zuul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

/**
 * @SpringCloudApplication注解
 * 整合了@SpringBootApplication、@EnableEurekaClient、@EnableCircuitBreaker
 * 主要目的还是简化配置
 */
@EnableZuulProxy
@SpringCloudApplication
public class ZuulApplication {

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

}
2.4 运行效果

从执行结果可以说明zuul起到了路由的作用

3、过滤器

可以通过zuul提供的过滤器,进行一些请求过滤,比如安全验证。

停止模块,增加过滤器类如下。

代码语言:javascript
复制
package com.cntaiping.tpa.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class TokenFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(TokenFilter.class);

   /**
    返回一个字符串代表过滤器的类型,
    pre:路由之前
    routing:路由之时
    post: 路由之后
    error:发送错误调用
   */
    @Override
    public String filterType() {
        return "pre";
    }

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

    /**
      这里可以写逻辑判断,是否要过滤,本文true,永远过滤。
    */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
      过滤器的具体逻辑。
   */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}
            return null;
        }
        log.info("ok");
        return null;
    }
}

重新运行模块

http://localhost:8400/api-a/hello?name=chengyq&token=111

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年05月31日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、Zuul简介
  • 2、新建模块
    • 2.1 pom文件
      • 2.2 application.properties
        • 2.3 Application类
          • 2.4 运行效果
          • 3、过滤器
          相关产品与服务
          负载均衡
          负载均衡(Cloud Load Balancer,CLB)提供安全快捷的流量分发服务,访问流量经由 CLB 可以自动分配到云中的多台后端服务器上,扩展系统的服务能力并消除单点故障。负载均衡支持亿级连接和千万级并发,可轻松应对大流量访问,满足业务需求。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档