当前位置: 首页 > news >正文

Spring Cloud Alibaba: Gateway 网关过滤器 GatewayGatewayFilter factory (记录)

目录

AddRequestHeader GatewayFilter factory

AddRequestHeadersIfNotPresent GatewayFilter factory

AddRequestParameter GatewayFilter Factory

AddResponseHeader GatewayFilter Factory

CircuitBreaker GatewayFilter factory

circuit breaker based on the status code

PrefixPath GatewayFilter factory

StripPrefix GatewayFilter factory

RewritePath GatewayFilter factory

RequestRateLimiter GatewayFilter factory

default-filters

自定义GatewayFilter

多filter的运行


AddRequestHeader GatewayFilter factory

添加对应key和value

server:port: 9000
​
spring:cloud:gateway:routes:- id: my_routeuri: http://localhost:7070predicates:- Path=/info/**filters:- AddRequestHeader=X-Request-Color, blue

controller获取请求头遍历输出

postman加请求头也能输出

AddRequestHeadersIfNotPresent GatewayFilter factory

可以添加多组key和value(请求头不存在对应key的情况下)

server:port: 9000
​
spring:cloud:gateway:routes:- id: my_routeuri: http://localhost:7070predicates:- Path=/info/**filters:- AddRequestHeadersIfNotPresent=X-Request-Color:blue,school:rjxy
@GetMapping("/allHeaders")public String allHeadersHandle(HttpServletRequest request){StringBuilder sb = new StringBuilder();//获取请求头所有的keyEnumeration<String> headerNames = request.getHeaderNames();//遍历所有keywhile (headerNames.hasMoreElements()) {//获取keyString name = headerNames.nextElement();sb.append(name+"===");//获取当前key的所有valueEnumeration<String> headers = request.getHeaders(name);//遍历所有valuewhile (headers.hasMoreElements()) {//将当前遍历的value追加到sb中sb.append(headers.nextElement()+"");}sb.append("<br>");
​}return sb.toString();}

controller进行请求头遍历输出,添加成功

 

AddRequestParameter GatewayFilter Factory

添加请求参数

server:port: 9000
​
spring:cloud:gateway:routes:- id: my_routeuri: http://localhost:7070predicates:- Path=/info/**filters:- AddRequestParameter=red, blue

controller

@GetMapping("/params")public String paramsHandle(String red){
​return red;}

 

获取成功

AddResponseHeader GatewayFilter Factory

响应修改

server:port: 9000
​
spring:cloud:gateway:routes:- id: my_routeuri: http://localhost:7070predicates:- Path=/info/**filters:- AddResponseHeader=X-Response-color, Blue- AddResponseHeader=X-Response-color, Red

直接F12查看响应头,添加成功

 

CircuitBreaker GatewayFilter factory

熔断过滤工厂,完成网关层的服务熔断与降级

server:port: 9000
​
spring:cloud:gateway:routes:- id: my_routeuri: http://localhost:7070predicates:- Path=/info/**filters:- name: CircuitBreakerargs:name: myCircuitBreakerfallbackUri: forward:/fb

访问http://localhost:7070不成功时,降级访问forward:/fb

降级controller

@GetMapping("/fb")public String fallbackHandle(){return "This is the Gateway Fallback";}

测试,直接不启动7070,访问9000,熔断成功

 

circuit breaker based on the status code

PrefixPath GatewayFilter factory

server:port: 9000
​
spring:cloud:gateway:routes:- id: my_routeuri: http://localhost:8081predicates:- Path=/student/**filters:- PrefixPath=/provider

匹配字段,加上前缀,子模块自动添加路径

 

测试成功

StripPrefix GatewayFilter factory

去除指定的请求路径

server:port: 9000
​
spring:cloud:gateway:routes:- id: my_routeuri: http://localhost:8081predicates:- Path=/aa/bb/provider/student/**filters:- StripPrefix=2

去除/aa/bb

 

测试成功

RewritePath GatewayFilter factory

重写路径

server:port: 9000
​
spring:cloud:gateway:routes:- id: my_routeuri: http://localhost:8081predicates:- Path=/red/blue/**filters:- RewritePath=/red/blue,/provider/student//            - RewritePath=/red/?(?<segment>.*), /$\{segment}

匹配路径,替换成指定路径

 

RequestRateLimiter GatewayFilter factory

通过令牌桶算法对进来的请求进行限流

导入依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis-reactive -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis-reactive</artifactId><version>3.0.5</version>
</dependency>

添加限流键解析器

在启动类中添加一个限流键解析器,其用于从请求中解析出需要限流的key。

本例指定的是根据请求的host或ip进行限流。

package com.guo;
​
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;
​
@SpringBootApplication
public class Application {
​public static void main(String[] args) {SpringApplication.run(Application.class, args);}
​@BeanKeyResolver userKeyResolver() {return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());}
}

修改配置文件

server:port: 9000
​
​
​
spring:cloud:gateway:routes:- id: my_routeuri: http://localhost:8081predicates:- Path=/**filters:
#              replenishRate 填充率- name: RequestRateLimiterargs:key-resolver: "#{@userKeyResolver}"redis-rate-limiter.replenishRate: 2redis-rate-limiter.burstCapacity: 5redis-rate-limiter.requestedTokens: 1data:redis:host: 127.0.0.1port: 6379

 

成功

default-filters

server:port: 9000
​
spring:cloud:gateway:default-filters:- AddRequestHeader=X-Request-Color, Default-Blueroutes:- id: my_routeuri: http://localhost:7070predicates:- Path=/info/header
​- id: my_routeuri: http://localhost:7070predicates:- Path=/info/headers

 

测试成功

自定义GatewayFilter

AddHeaderGatewayFilter.java

public class AddHeaderGatewayFilter implements GatewayFilter {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest().mutate().header("X-Request-Color", "filter-Red").build();ServerWebExchange webExchange = exchange.mutate().request(request).build();return chain.filter(webExchange);}
}

调用自定义的GatewayFilter

@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder){return builder.routes().route("my_router2",ps ->ps.path("/info/**").filters(fs->fs.filter(new AddHeaderGatewayFilter())).uri("http://localhost:7070")).build();
}

 

测试成功

多filter的运行

OneGateWayFilter.java

@Slf4j
public class OneGateWayFilter implements GatewayFilter {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {long startTime = System.currentTimeMillis();log.info("oneFilter-pre:"+startTime);exchange.getAttributes().put("startTime",startTime);return chain.filter(exchange).then(Mono.fromRunnable(()->{log.info("oneFilter------post");Long startTimeAttr = (Long) exchange.getAttributes().get("startTime");long elaspedTime = System.currentTimeMillis() - startTimeAttr;log.info("所有过滤器执行的时间(毫秒)为:"+elaspedTime);}));}
}

TwoGateWayFilter.java

@Slf4j
public class TwoGateWayFilter implements GatewayFilter {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {log.info("TwoFilter----pre");return chain.filter(exchange).then(Mono.fromRunnable(()->{log.info("TwoFilter------post");}));}
}

ThreeGateWayFilter.java

@Slf4j
public class ThreeGateWayFilter implements GatewayFilter {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {log.info("ThreeFilter----pre");return chain.filter(exchange).then(Mono.fromRunnable(()->{log.info("ThreeFilter------post");}));}
}

 

测试结果

http://www.lryc.cn/news/66074.html

相关文章:

  • Windows Server 2016版本说明
  • 车载红外夜视「升温」
  • ext3 文件系统的特点、优缺点以及使用场景
  • rk3568 修改开机logo
  • golang实现关键路径算法
  • Overcoming catastrophic forgetting in neural networks
  • [Linux] Linux文件系统
  • 有仰拍相机和俯拍相机时,俯拍相机中心和吸嘴中心的标定
  • 【Vue学习笔记5】Vue3中的响应式:ref和reactive、watchEffect和watch
  • 自动化测试工具的基本原理以及应用场景
  • 《Java虚拟机学习》 java代码的运行过程
  • 关于Intel处理器架构中AVX2里Gather特性的说明
  • UNIX常用命令(C站最全,一文通关)
  • Vue监听属性详细讲解
  • 网申形式一览:这三种投递方式,你了解吗?
  • vue项目将多张图片生成一个gif动图
  • 开心档之Go 语言常量
  • 动态库和静态库的使用
  • 前端:20 个常见的前端算法题
  • 【Linux】多线程 --- 线程概念 控制 封装
  • 最长递增子序列的长度 _ 贪心+二分查找 _ 20230510
  • VMware ESXi 7.0 U3m Unlocker OEM BIOS 集成网卡驱动和 NVMe 驱动 (集成驱动版)
  • Scrum敏捷开发和项目管理流程及工具
  • 微服务之配置中心
  • windows下安装OpenCL
  • 前端项目的通用优化策略
  • 关于 IO、存储、硬盘和文件系统
  • 计算机网络期中复习提纲-酷酷的聪整理版
  • clickhouse的嵌套数据结构Tuple、Array与Nested类型介绍和使用示例
  • 人脸修复增强调研