网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

SpringCloud入门教程-Zuul实现API网关和请求过滤-创新互联

简介

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

成都创新互联专注为客户提供全方位的互联网综合服务,包含不限于网站设计制作、成都网站设计、宁海网络推广、微信小程序定制开发、宁海网络营销、宁海企业策划、宁海品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们大的嘉奖;成都创新互联为所有大学生创业者提供宁海建站搭建服务,24小时服务热线:028-86922220,官方网址:www.cdcxhl.com
  • 认证
  • 过滤
  • 压力测试
  • 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也会自动进行负载均衡。

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

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

另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


文章名称:SpringCloud入门教程-Zuul实现API网关和请求过滤-创新互联
当前URL:http://bjjierui.cn/article/deggdg.html

其他资讯