自研網(wǎng)關(guān):限流功能的開發(fā)

自研網(wǎng)關(guān)系統(tǒng)已開源,求star
項(xiàng)目地址:

網(wǎng)關(guān)系統(tǒng),如果沒有限流功能,感覺就沒有了靈魂。
所以一直想把限流功能加上。
經(jīng)查資料,實(shí)現(xiàn)功能如下:

限流功能配置

測試限流功能

具體實(shí)現(xiàn)如下:

@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項(xiàng)目
具體代碼大家可以去我的開源項(xiàng)目中看,歡迎提ISSUE及需求。
因?yàn)橹挥幸粋€(gè)人,也歡迎大家參與進(jìn)來.

網(wǎng)關(guān)系統(tǒng)暫時(shí)一段落,后面只修改缺陷不新增功能,主要是人不夠,只有我一個(gè)人
其實(shí)網(wǎng)關(guān)還有很多我想做的。

  1. 協(xié)議泛化功能,將dubbo轉(zhuǎn)http,將webservice轉(zhuǎn)http
  2. 特定的日志查詢與跟蹤。需要將部分的日志做特殊處理,好做數(shù)據(jù)分析及跟蹤
  3. 引入GraphQl,將普通的Rest接口轉(zhuǎn)成GraphQl接口
    可惜我一個(gè)人忙不過來
    下期計(jì)劃:
    流程引擎(暫未開源)
    1。增加機(jī)器人節(jié)點(diǎn),可考慮做RPA的相關(guān)事情
    2。優(yōu)化流程圖設(shè)計(jì)器,這方面涉及前端,不太擅長
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容