Spring Cloud入门教程 - Zuul实现API网关和请求过滤
admin
2023-03-11 16:02:37
0

简介

Zuul是Spring Cloud提供的api网关和过滤组件,它提供如下功能:

  • 认证
  • 过滤
  • 压力测试
  • Canary测试
  • 动态路由
  • 服务迁移
  • 负载均衡
  • 安全
  • 静态请求处理
  • 动态流量管理

在本教程中,我们将用zuul,把web端的请求/product转发到对应的产品服务上,并且定义一个pre过滤器来验证是否经过了zuul的转发。

基础环境

  • JDK 1.8
  • Maven 3.3.9
  • IntelliJ 2018.1
  • Git

项目源码

Gitee码云

创建Zuul服务

在IntelliJ中创建一个maven项目:

  • cn.zxuqian
  • apiGateway

然后在pom.xml中添加如下代码:



    4.0.0

    cn.zxuqian
    apiGateway
    1.0-SNAPSHOT

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.1.RELEASE
    

    
        
            org.springframework.cloud
            
            spring-cloud-starter-netflix-zuul
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.cloud
            spring-cloud-starter-config
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.springframework.boot
            spring-boot-starter-web
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Finchley.M9
                pom
                import
            
        
    

    
        1.8
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

    
        
            spring-milestones
            Spring Milestones
            https://repo.spring.io/libs-milestone
            
                false
            
        
    

需要注意的是,Spring官网的教程给的zuul的artifactId为spring-cloud-starter-zuul,这个是旧版zuul的名字,在我们的Finchley.M9版本中已经更名为spring-cloud-starter-netflix-zuul

添加src/main/resources/bootstrap.yml文件,指定spring.application.name

spring:
  application:
    name: zuul-server

创建cn.zxuqian.Application类:

package cn.zxuqian;

import cn.zxuqian.filters.PreFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;

@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class Application {

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

    @Bean
    public PreFilter preFilter() {
        return new PreFilter();
    }
}

这里使用了@EnableZuulProxy来指定使用zuul的反向代理,把我们的请求转发到对应的服务器上。然后启用了eureka的服务发现。Zuul默认也会使用Ribbon做负载均衡,所以可以通过eureka发现已注册的服务。PreFilter是一个预过滤器,用来在request请求被处理之前进行一些操作,它的代码如下:

package cn.zxuqian.filters;

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 javax.servlet.http.HttpServletRequest;

public class PreFilter extends ZuulFilter {

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

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @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()));

        return null;
    }
}

filterType - Zuul内置的filter类型有四种,pre, routeposterror,分别代表请求处理前,处理时,处理后和出错后。
filterOrder - 指定了该过滤器执行的顺序。
shouldFilter - 是否开启此过滤器。
run - 过滤器的业务逻辑。这里只是简单的log了一下reqeust的请求方式和请求的路径。

接下来,在我们的配置中心的git仓库中创建zuul-server.yml文件,并添加如下配置:

server:
  port: 8083
zuul:
  routes:
    products:
      path: /product/**
      serviceId: product-service

这里配置了zuul的端口为8083,然后映射所有/product/的请求到我们的product-service服务上。如果不配置serviceId,那么products这个Key就会默认作为ServiceId,而我们的例子中,ServiceId包括了-,所以在下边显示指定了ServiceId。配置完成后提交到git。

更新productService

productService的uri做了一点改动,使其更符合rest风格:

@RequestMapping("/list")
public String productList() {
    log.info("Access to /products endpoint");
    return "外套,夹克,毛衣,T恤";
}

这里@RequestMapping匹配的路径改为了/list,之前是/products

更新web客户端

在我们的web客户端的ProductService中添加一个新的方法:

public String productListZuul() {
    return this.restTemplate.getForObject("http://zuul-server/product/list", String.class);
}

这次我们直接请求zuul-server服务,然后由它把我们的请求反射代理到product-service服务。最后在ProductController中添加一个请求处理方法:

@RequestMapping("/product/list")
public String productListZuul() {
    return productService.productListZuul();
}

用来处理/product/list请求,然后调用ProductService类中的方法。

测试

使用mvn spring-boot:run启动configServerregistry, zuulServer, productServiceweb这几个工程,然后启动第二个productService,使用SERVER_PORT=8082 spring-boot:run
访问几次http://localhost:8080/product/list,然后除了会在浏览器看到返回的结果,我们还会在zuulServer的命令行窗口中看到如下字样:

GET 方式请求 http://xuqians-imac:8083/product/list

然后在两个productService的命令行窗口中,我们还会看到随机出现的

Access to /products endpoint

说明zuulServer也会自动进行负载均衡。

欢迎访问我的博客张旭乾的博客

大家有什么想法欢迎来讨论。

相关内容

热门资讯

AI专题:AI原生基础设施实践... 今天分享的是:AI专题:AI原生基础设施实践指南(2026) 报告共计:73页 《AI原生基础设施实...
终于明白“荊州晃晃麻将.怎么装... 家人们!今天小编来为大家解答荊州晃晃麻将透视挂怎么安装这个问题咨询软件客服徽9784099的挂在哪里...
最新引进“新人海炸金花.可以开... 有 亲,根据资深记者爆料新人海炸金花是可以开挂的,确实有挂(咨询软件无需...
重磅消息“麻友圈2贵阳捉鸡.是... 您好:麻友圈2贵阳捉鸡这款游戏可以开挂,确实是有挂的,需要了解加客服微信【4282891】很多玩家在...
我来教教您“福建兄弟十三水.真... 您好:福建兄弟十三水这款游戏可以开挂,确实是有挂的,需要了解加客服微信【9784099】很多玩家在这...
【第一财经】“战神牛牛.开挂神... 【第一财经】“战神牛牛.开挂神器?”太坑了果然有挂您好,战神牛牛这个游戏其实有挂的,确实是有挂的,需...
最新引进“天涯麻将.到底有挂吗... 有 亲,根据资深记者爆料天涯麻将是可以开挂的,确实有挂(咨询软件无需打开...
玩家分享攻略“红黑大战.到底是... 玩家分享攻略“红黑大战.到底是不是挂?”必胜开挂神器您好,红黑大战这个游戏其实有挂的,确实是有挂的,...
【今日要闻】“阿拉游戏中心.有... 您好:阿拉游戏中心这款游戏可以开挂,确实是有挂的,需要了解加客服微信【9784099】很多玩家在这款...
终于了解“咸宁晃晃麻将.到底有... 网上科普关于“咸宁晃晃麻将有没有挂”话题很是火热,小编也是针对咸宁晃晃麻将作*弊开挂的方法以及开挂对...