自研网关系统已开源,求star 项目地址:
网关系统,如果没有限流功能,感觉就没有了灵魂。 所以一直想把限流功能加上。 经查资料,实现功能如下:
限流功能配置
测试限流功能
具体实现如下:
@Slf4j
@Component
public class GatewayRedisRateLimiter implements InitializingBean {
@Autowired
@Lazy
private RedisTemplate stringRedisTemplate;
private RedisScript<List<Long>> script;
private AtomicBoolean initialized = new AtomicBoolean(false);
/**
* This uses a basic token bucket algorithm and relies on the fact that Redis scripts
* execute atomically. No other operations can run between fetching the count and
* writing the new count.
*
* @param key is rule id
* @param replenishRate replenishRate
* @param burstCapacity burstCapacity
* @return {@code Mono<Response>} to indicate when request processing is complete
*/
public Boolean isAllowed(final String key, final double replenishRate, final double burstCapacity) {
if (!this.initialized.get()) {
throw new IllegalStateException("RedisRateLimiter is not initialized");
}
List<String> keys = getKeys(key);
String[] scriptArgs = new String[]{replenishRate + "", burstCapacity + "", Instant.now().getEpochSecond() + "", "1"};
List<Long> resultFlux = (List<Long>) stringRedisTemplate.execute(this.script, keys, scriptArgs);
if (CollectionUtils.isEmpty(resultFlux)) {
resultFlux = Arrays.asList(1L, -1L);
}
boolean allowed = resultFlux.get(0) == 1L;
Long tokensLeft = resultFlux.get(1);
log.info("RateLimiter key:{},allowed:{},tokensLeft:{}", key, allowed, tokensLeft);
return allowed;
}
private static List<String> getKeys(final String id) {
String prefix = "request_rate_limiter.{" + id;
String tokenKey = prefix + "}.tokens";
String timestampKey = prefix + "}.timestamp";
return Arrays.asList(tokenKey, timestampKey);
}
@SuppressWarnings("unchecked")
private RedisScript<List<Long>> redisScript() {
DefaultRedisScript redisScript = new DefaultRedisScript<>();
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("/META-INF/scripts/request_rate_limiter.lua")));
redisScript.setResultType(List.class);
return redisScript;
}
@Override
public void afterPropertiesSet() {
this.script = redisScript();
initialized.compareAndSet(false, true);
}
}
这是主要的核心代码,可用于普通的spring mvc项目 具体代码大家可以去我的开源项目中看,欢迎提ISSUE及需求。 因为只有一个人,也欢迎大家参与进来.
网关系统暂时一段落,后面只修改缺陷不新增功能,主要是人不够,只有我一个人 其实网关还有很多我想做的。