html5网站模板免费下载,宜春网站建设公司哪家好,一个考试网站怎么做,沈阳祥云医院男科怎么样令牌桶算法配合 Redis 在 Java 中的应用令牌桶算法是一种常用的限流算法#xff0c;适用于控制请求的频率#xff0c;防止系统过载。结合 Redis 使用可以实现高效的分布式限流。
一.、引入依赖首先#xff0c;需要在 pom.xml 文件中引入 spring-boot-starter-data-re… 令牌桶算法配合 Redis 在 Java 中的应用令牌桶算法是一种常用的限流算法适用于控制请求的频率防止系统过载。结合 Redis 使用可以实现高效的分布式限流。
一.、引入依赖首先需要在 pom.xml 文件中引入 spring-boot-starter-data-redis 依赖这个依赖提供了与 Redis 交互的客户端和工具类。
dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependency
/dependencies二.、配置 Redis 连接 我随便用了application.properties 也可以用 application.yml
spring.redis.hostlocalhost
spring.redis.port6379
spring.redis.password
spring.redis.jedis.pool.max-active8
spring.redis.jedis.pool.max-wait-1
spring.redis.jedis.pool.max-idle8
spring.redis.jedis.pool.min-idle0
spring.redis.timeout2000
三.、实现令牌桶算法
使用 Lua 脚本和 Redis 操作来实现令牌桶算法。在resources创建一个 Lua 脚本文件 request_rate_limiter.lua
-- 获取到限流资源令牌数的key和响应时间戳的key
local tokens_key KEYS[1]
local timestamp_key KEYS[2]
-- 分别获取填充速率、令牌桶容量、当前时间戳、消耗令牌数
local rate tonumber(ARGV[1])
local capacity tonumber(ARGV[2])
local now tonumber(ARGV[3])
local requested tonumber(ARGV[4])
-- 计算出失效时间大概是令牌桶填满时间的两倍
local fill_time capacity / rate
local ttl math.floor(fill_time * 2)
-- 获取到最近一次的剩余令牌数如果不存在说明令牌桶是满的
local last_tokens tonumber(redis.call(get, tokens_key))
if last_tokens nil thenlast_tokens capacity
end
-- 上次消耗令牌的时间戳不存在视为0
local last_refreshed tonumber(redis.call(get, timestamp_key))
if last_refreshed nil thenlast_refreshed 0
end
-- 计算出间隔时间
local delta math.max(0, now - last_refreshed)
-- 剩余令牌数量 “令牌桶容量” 和 “最后令牌数填充速率*时间间隔”之间的最小值
local filled_tokens math.min(capacity, last_tokens (delta * rate))
-- 如果剩余令牌数量大于等于消耗令牌的数量则流量通过否则不通过
local allowed filled_tokens requested
local new_tokens filled_tokens
local allowed_num 0
if allowed thennew_tokens filled_tokens - requestedallowed_num 1
end
-- 更新令牌桶状态
if ttl 0 thenredis.call(setex, tokens_key, ttl, new_tokens)redis.call(setex, timestamp_key, ttl, now)
end
return allowed_num四、创建一个 TokenBucket 类使用 StringRedisTemplate 执行 Lua 脚本。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;import javax.xml.crypto.Data;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;Component
public class TokenBucket {private static final String TOKEN_BUCKET_KEY_PREFIX rate_limiter:;private static final String LUA_SCRIPT_PATH request_rate_limiter.lua;Autowiredprivate StringRedisTemplate stringRedisTemplate;public boolean tryAccess(String key, int limitCount, int refillRate) {String luaScript loadLuaScript();// 使用加载的Lua脚本创建一个RedisScript 对象。 DefaultRedisScript 是Spring Data Redis提供的一个类用于封装Lua脚本。RedisScriptLong redisScript new DefaultRedisScript(luaScript, Long.class);// TOKEN_BUCKET_KEY_PREFIX key :tokens用于存储令牌桶中的令牌数量。•// TOKEN_BUCKET_KEY_PREFIX key :timestamp用于存储上一次令牌桶被填充的时间戳。ListString keys Arrays.asList(TOKEN_BUCKET_KEY_PREFIX key :tokens, TOKEN_BUCKET_KEY_PREFIX key :timestamp);//执行Lua脚本/*** 使用 StringRedisTemplate 执行Lua脚本。execute方法的参数包括* • redisScript Lua脚本对象。* • keysRedis键列表。* • String.valueOf(refillRate)令牌桶的填充速率。* • String.valueOf(limitCount)令牌桶的最大容量。* • String.valueOf(System.currentTimeMillis() / 1000)当前时间戳秒级。* • 1 请求的令牌数量这里假设每次请求需要1个令牌。*/Long result stringRedisTemplate.execute(redisScript, //Lua脚本对象。keys, //Redis键列表String.valueOf(refillRate), //令牌桶的填充速率String.valueOf(limitCount), //令牌桶的最大容量String.valueOf(System.currentTimeMillis() / 1000), //当前时间戳秒级1 //请求的令牌数量这里假设每次请求需要1个令牌。);return result ! null result 1;}private String loadLuaScript() {InputStreamReader reader null;try {//使用类加载器从指定路径 LUA_SCRIPT_PATH 获取资源流。我的lua文件在resources根目录下面//使用 InputStreamReader 将输入流 resourceStream 包装成一个字符流并指定字符编码为UTF-8。这样可以确保读取的文件内容是正确的编码格式reader new InputStreamReader(getClass().getClassLoader().getResourceAsStream(LUA_SCRIPT_PATH), StandardCharsets.UTF_8);/*创建一个Scanner对象用于读取字符流。useDelimiter(\\A)设置分隔符为文件的开始标记 \\A 。这意味着Scanner会将整个文件内容视为一个单一的字符串。next() 读取并返回整个文件内容*/return new java.util.Scanner(reader).useDelimiter(\\A).next();} catch (Exception e) {throw new RuntimeException(Failed to load Lua script, e);}}
}五、测试
package com.lhx.testany.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;RestController
public class RateLimiterController {Autowiredprivate TokenBucket tokenBucket;GetMapping(/test)public String testRateLimiter() {//为了测试把最多设成2个令牌每秒只生成1个令牌, 我快速在浏览器调用时//生成的令牌不足于被消耗就会执行esle,这样就能做限流if (tokenBucket.tryAccess(api1, 2, 1)) {return Request allowed;} else {return Request denied due to rate limit;}}
} 文章转载自: http://www.morning.qlck.cn.gov.cn.qlck.cn http://www.morning.qlpq.cn.gov.cn.qlpq.cn http://www.morning.mwpcp.cn.gov.cn.mwpcp.cn http://www.morning.dbrnl.cn.gov.cn.dbrnl.cn http://www.morning.tpmnq.cn.gov.cn.tpmnq.cn http://www.morning.hqykb.cn.gov.cn.hqykb.cn http://www.morning.skrh.cn.gov.cn.skrh.cn http://www.morning.tgqzp.cn.gov.cn.tgqzp.cn http://www.morning.qkcyk.cn.gov.cn.qkcyk.cn http://www.morning.pgfkl.cn.gov.cn.pgfkl.cn http://www.morning.sgfnx.cn.gov.cn.sgfnx.cn http://www.morning.rkdw.cn.gov.cn.rkdw.cn http://www.morning.dnhdp.cn.gov.cn.dnhdp.cn http://www.morning.hnhsym.cn.gov.cn.hnhsym.cn http://www.morning.zpkfb.cn.gov.cn.zpkfb.cn http://www.morning.ryywf.cn.gov.cn.ryywf.cn http://www.morning.gcxfh.cn.gov.cn.gcxfh.cn http://www.morning.qbfwb.cn.gov.cn.qbfwb.cn http://www.morning.btlmb.cn.gov.cn.btlmb.cn http://www.morning.kfrhh.cn.gov.cn.kfrhh.cn http://www.morning.rblqk.cn.gov.cn.rblqk.cn http://www.morning.rpjr.cn.gov.cn.rpjr.cn http://www.morning.znqfc.cn.gov.cn.znqfc.cn http://www.morning.ysgnb.cn.gov.cn.ysgnb.cn http://www.morning.gmysq.cn.gov.cn.gmysq.cn http://www.morning.nclbk.cn.gov.cn.nclbk.cn http://www.morning.mftzm.cn.gov.cn.mftzm.cn http://www.morning.tdgwg.cn.gov.cn.tdgwg.cn http://www.morning.xtrnx.cn.gov.cn.xtrnx.cn http://www.morning.bfgbz.cn.gov.cn.bfgbz.cn http://www.morning.dnqliv.cn.gov.cn.dnqliv.cn http://www.morning.pjbhk.cn.gov.cn.pjbhk.cn http://www.morning.kfwrq.cn.gov.cn.kfwrq.cn http://www.morning.zrnph.cn.gov.cn.zrnph.cn http://www.morning.mcqhb.cn.gov.cn.mcqhb.cn http://www.morning.sryyt.cn.gov.cn.sryyt.cn http://www.morning.spghj.cn.gov.cn.spghj.cn http://www.morning.rqgbd.cn.gov.cn.rqgbd.cn http://www.morning.nbiotank.com.gov.cn.nbiotank.com http://www.morning.junmap.com.gov.cn.junmap.com http://www.morning.kfmlf.cn.gov.cn.kfmlf.cn http://www.morning.ndxmn.cn.gov.cn.ndxmn.cn http://www.morning.ckctj.cn.gov.cn.ckctj.cn http://www.morning.sjbpg.cn.gov.cn.sjbpg.cn http://www.morning.xbdrc.cn.gov.cn.xbdrc.cn http://www.morning.dnconr.cn.gov.cn.dnconr.cn http://www.morning.pcgjj.cn.gov.cn.pcgjj.cn http://www.morning.cknws.cn.gov.cn.cknws.cn http://www.morning.ygkb.cn.gov.cn.ygkb.cn http://www.morning.knnc.cn.gov.cn.knnc.cn http://www.morning.qtfss.cn.gov.cn.qtfss.cn http://www.morning.wbdm.cn.gov.cn.wbdm.cn http://www.morning.mlbdr.cn.gov.cn.mlbdr.cn http://www.morning.rwzmz.cn.gov.cn.rwzmz.cn http://www.morning.clgbb.cn.gov.cn.clgbb.cn http://www.morning.krjyq.cn.gov.cn.krjyq.cn http://www.morning.tqsmg.cn.gov.cn.tqsmg.cn http://www.morning.bmpjp.cn.gov.cn.bmpjp.cn http://www.morning.bflwj.cn.gov.cn.bflwj.cn http://www.morning.mtyhk.cn.gov.cn.mtyhk.cn http://www.morning.qqklk.cn.gov.cn.qqklk.cn http://www.morning.dzrcj.cn.gov.cn.dzrcj.cn http://www.morning.hdzty.cn.gov.cn.hdzty.cn http://www.morning.dkfb.cn.gov.cn.dkfb.cn http://www.morning.rgfx.cn.gov.cn.rgfx.cn http://www.morning.trffl.cn.gov.cn.trffl.cn http://www.morning.lbgfz.cn.gov.cn.lbgfz.cn http://www.morning.qddtd.cn.gov.cn.qddtd.cn http://www.morning.liyixun.com.gov.cn.liyixun.com http://www.morning.chehb.com.gov.cn.chehb.com http://www.morning.fwwkr.cn.gov.cn.fwwkr.cn http://www.morning.dpzcc.cn.gov.cn.dpzcc.cn http://www.morning.qbtj.cn.gov.cn.qbtj.cn http://www.morning.ysnbq.cn.gov.cn.ysnbq.cn http://www.morning.fosfox.com.gov.cn.fosfox.com http://www.morning.zcfmb.cn.gov.cn.zcfmb.cn http://www.morning.whclz.cn.gov.cn.whclz.cn http://www.morning.yxwnn.cn.gov.cn.yxwnn.cn http://www.morning.pmdnx.cn.gov.cn.pmdnx.cn http://www.morning.xdpjs.cn.gov.cn.xdpjs.cn