Spring Cloud基础教程(七):路由网关使用(Zuul)

2024-05-24 13:08

本文主要是介绍Spring Cloud基础教程(七):路由网关使用(Zuul),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、概述

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

二、准备

将服务注册与发现这篇博客中的Eureka-Client-A工程,复制一份,名字修改为Service-Zuul。

三、工程修改

Gradle依赖修改为

dependencies {compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')compile('org.springframework.cloud:spring-cloud-starter-zuul:1.4.4.RELEASE')compile('org.springframework.boot:spring-boot-starter-web')testCompile('org.springframework.boot:spring-boot-starter-test')
}

在启动类上添加@EnableZuulProxy注解,开启路由功能。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class EurekaZuulApplication
{public static void main(String[] args) {SpringApplication.run(EurekaZuulApplication.class, args);}
}

修改application.properties配置文件,将/client-a/开头的请求路由到eureka-client-a服务器

spring.application.name=service-zuul
server.port=10010
eureka.client.serviceUrl.defaultZone=http://localhost:10001/eureka/zuul.routes.api-a.path: /client-a/**
zuul.routes.api-a.serviceId: eureka-client-a

四、测试

启动之前的Eureka-Server、Eureka-Client-A和当前的Service-Zuul工程,访问http://127.0.0.1:10001/


发现都已经注册到了注册中心,访问http://127.0.0.1:10010/client-a/client,会发现路由到了Eureka-Client-A


五、服务过滤

Zuul不仅有路由的功能,还有服务过滤的功能,做一些拦截验证。

新建MyFilter类

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;/*** Created by wzj on 2018/5/24.*/
@Component
public class MyFilter extends ZuulFilter
{private static Logger log = LoggerFactory.getLogger(MyFilter.class);/*** to classify a filter by type. Standard types in Zuul are "pre" for pre-routing filtering,* "route" for routing to an origin, "post" for post-routing filters, "error" for error handling.* We also support a "static" type for static responses see  StaticResponseFilter.* Any filterType made be created or added and run by calling FilterProcessor.runFilters(type)** @return A String representing that type*/@Overridepublic String filterType(){return "pre";}/*** filterOrder() must also be defined for a filter. Filters may have the same  filterOrder if precedence is not* important for a filter. filterOrders do not need to be sequential.** @return the int order of a filter*/@Overridepublic int filterOrder(){return 0;}/*** a "true" return from this method means that the run() method should be invoked** @return true if the run() method should be invoked. false will not invoke the run() method*/@Overridepublic boolean shouldFilter(){return true;}/*** if shouldFilter() is true, this method will be invoked. this method is the core method of a ZuulFilter** @return Some arbitrary artifact may be returned. Current implementation ignores it.* @throws ZuulException if an error occurs during execution.*/@Overridepublic 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;}
}

filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下: 

  • pre:路由之前
  • routing:路由之时
  • post: 路由之后
  • error:发送错误调用
  • filterOrder:过滤的顺序
  • shouldFilter:这里可以写逻辑判断,是否要过滤,本文true,永远过滤。
  • run:过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。

服务重启,再次访问http://127.0.0.1:10010/client-a/client,界面显示如下


再次输入http://127.0.0.1:10010/client-a/client?token=1001


这篇关于Spring Cloud基础教程(七):路由网关使用(Zuul)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/998490

相关文章

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF