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

相关文章

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do