日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

java同名过滤器_Gateway Redis令牌桶请求限流过滤器

發(fā)布時間:2025/3/21 数据库 54 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java同名过滤器_Gateway Redis令牌桶请求限流过滤器 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

spring cloud gateway默認(rèn)基于redis令牌桶算法進(jìn)行微服務(wù)的限流保護(hù),采用RateLimter限流算法來實現(xiàn)。

1、引入依賴包

org.springframework.cloud

spring-cloud-starter-gateway

org.springframework.cloud

spring-cloud-starter-netflix-hystrix

org.springframework.cloud

spring-cloud-starter-circuitbreaker-resilience4j

org.springframework.cloud

spring-cloud-starter-circuitbreaker-reactor-resilience4j

org.springframework.boot

spring-boot-starter-data-redis-reactive

2、yml中配置redis

spring:

application:

name: mima-cloud-gateway

redis:

database: 1

host: localhost

port: 6379

password:

3、配置KeyResolver——RateLimiteConfig.java(接口限流/ip限流/用戶限流)

package com.mkevin.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import reactor.core.publisher.Mono;

/**

* 限流配置KeyResolver——有三種寫法(接口限流/ip限流/用戶限流)

*/

@Configuration

public class RateLimiteConfig {

/**

* 接口限流:根據(jù)請求路徑限流

* @return

*/

/*

如果不使用@Primary注解,會報如下錯誤,需要注意

Description:

Parameter 1 of method requestRateLimiterGatewayFilterFactory in org.springframework.cloud.gateway.config.GatewayAutoConfiguration required a single bean, but 3 were found:

- pathKeyResolver: defined by method 'pathKeyResolver' in class path resource [com/mkevin/gateway/config/RateLimiteConfig.class]

- ipKeyResolver: defined by method 'ipKeyResolver' in class path resource [com/mkevin/gateway/config/RateLimiteConfig.class]

- userKeyResolver: defined by method 'userKeyResolver' in class path resource [com/mkevin/gateway/config/RateLimiteConfig.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier

to identify the bean that should be consumed

*/

@Bean

@Primary

public KeyResolver pathKeyResolver() {

//寫法1

return exchange -> Mono.just(

exchange.getRequest()

.getPath()

.toString()

);

/*

//寫法2

return new KeyResolver() {

@Override

public Mono resolve(ServerWebExchange exchange) {

return Mono.just(exchange.getRequest()

.getPath()

.toString());

}

};

*/

}

/**

* 根據(jù)請求IP限流

* @return

*/

@Bean

public KeyResolver ipKeyResolver() {

return exchange -> Mono.just(

exchange.getRequest()

.getRemoteAddress()

.getHostName()

);

}

/**

* 根據(jù)請求參數(shù)中的userId進(jìn)行限流

*

* 請求地址寫法:http://localhost:8801/rate/123?userId=lisi

*

* @return

*/

@Bean

public KeyResolver userKeyResolver() {

return exchange -> Mono.just(

exchange.getRequest()

.getQueryParams()

.getFirst("userId")

);

}

}

4、yml中配置spring.cloud.gateway.routes.filters

spring:

cloud:

gateway:

routes:

- id: rate-limit-demo

uri: lb://mima-cloud-producer

predicates:

#訪問路徑:http://localhost:8801/rate/123

- Path=/rate/**

filters:

- name: RequestRateLimiter

args:

# 令牌桶每秒填充平均速率, 允許用戶每秒處理多少個請求。

redis-rate-limiter.replenishRate: 1

# 令牌桶的容量,允許在1s內(nèi)完成的最大請求數(shù)。

redis-rate-limiter.burstCapacity: 2

# 使用SpEL表達(dá)式從Spring容器中獲取Bean對象, 查看RateLimiteConfig實現(xiàn)類中的方法名

key-resolver: "#{@pathKeyResolver}"

#key-resolver: "#{@ipKeyResolver}"

#key-resolver: "#{@userKeyResolver}"

當(dāng)F5頻繁刷新請求接口時,控制臺會報429錯誤狀態(tài)碼,提示我們請求過多,如下:

[開始]請求路徑:/rate/123

[應(yīng)答]請求路徑:/rate/123耗時:2ms

2020-09-08 16:23:27.253 DEBUG 18512 --- [ioEventLoop-4-1] o.s.w.s.adapter.HttpWebHandlerAdapter : [62eb90e0] Completed 429 TOO_MANY_REQUESTS

2020-09-08 16:23:27.394 DEBUG 18512 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter : [62eb90e0] HTTP GET "/rate/123"

corsFilter... run

[開始]請求路徑:/rate/123

[應(yīng)答]請求路徑:/rate/123耗時:2ms

2020-09-08 16:23:27.397 DEBUG 18512 --- [ioEventLoop-4-1] o.s.w.s.adapter.HttpWebHandlerAdapter : [62eb90e0] Completed 429 TOO_MANY_REQUESTS

2020-09-08 16:23:27.536 DEBUG 18512 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter : [62eb90e0] HTTP GET "/rate/123"

corsFilter... run

6、當(dāng)發(fā)生限流時,會向redis中存儲兩個數(shù)據(jù)

127.0.0.1:1>keys *

1) "request_rate_limiter.{/rate/123}.timestamp"

2) "request_rate_limiter.{/rate/123}.tokens"

127.0.0.1:1>keys *

1) "request_rate_limiter.{0:0:0:0:0:0:0:1}.timestamp"

2) "request_rate_limiter.{0:0:0:0:0:0:0:1}.tokens"

127.0.0.1:1>keys *

1) "request_rate_limiter.{lisi}.timestamp"

2) "request_rate_limiter.{lisi}.tokens"

參數(shù)說明:

request_rate_limiter.{key}.timestamp:

存儲的是當(dāng)前時間的秒數(shù),也就是System.currentTimeMillis()/1000或者Instant.now().getEpochSecond()。

request_rate_limiter.{key}.tokens:

存儲的是當(dāng)前這秒鐘對應(yīng)的可用令牌數(shù)量

7、完整yml配置文件

# 開啟resilience4j斷路器

# spring.cloud.circuitbreaker.resilience4j.enabled: true

# 設(shè)置hystrix斷路器超時時間

# hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 2000

spring:

application:

name: mima-cloud-gateway

redis:

database: 1

host: localhost

port: 6379

password:

cloud:

gateway:

routes:

- id: rate-limit-demo

uri: lb://mima-cloud-producer

predicates:

#訪問路徑:http://localhost:8801/rate/123

- Path=/rate/**

filters:

- name: RequestRateLimiter

args:

# 令牌桶每秒填充平均速率, 允許用戶每秒處理多少個請求。

redis-rate-limiter.replenishRate: 1

# 令牌桶的容量,允許在1s內(nèi)完成的最大請求數(shù)。

redis-rate-limiter.burstCapacity: 2

# 使用SpEL表達(dá)式從Spring容器中獲取Bean對象, 查看RateLimiteConfig實現(xiàn)類中的同名方法

#key-resolver: "#{@pathKeyResolver}"

#key-resolver: "#{@ipKeyResolver}"

#請求地址寫法:http://localhost:8801/rate/123?userId=lisi

key-resolver: "#{@userKeyResolver}"

# The RequestRateLimiter GatewayFilter Factory

# The Redis RateLimiter

# Modify a Request Body GatewayFilter Factory 測試版本,未來可能改動

# Modify a Response Body GatewayFilter Factory 測試版本,未來可能改動

server:

port: 8801

eureka:

client:

serviceUrl:

#defaultZone: http://kevin:123456@localhost:8761/eureka/

defaultZone: http://localhost:8761/eureka/

instance:

prefer-ip-address: true

#instance-id: ${spring.application.name}:${spring.cloud.client.ip-address:}:${server.port}

instance-id: ${spring.application.name}:${server.port}

debug: true

management:

endpoints:

web:

exposure:

include: '*'

endpoint:

health:

show-details: always

shutdown: true

https://www.cnblogs.com/linjiqin/category/1301747.html

總結(jié)

以上是生活随笔為你收集整理的java同名过滤器_Gateway Redis令牌桶请求限流过滤器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。