前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >自研网关:限流功能的开发

自研网关:限流功能的开发

作者头像
星痕
发布2020-10-26 17:42:08
4320
发布2020-10-26 17:42:08
举报
文章被收录于专栏:JAVA后端开发JAVA后端开发

自研网关系统已开源,求star 项目地址:

网关系统,如果没有限流功能,感觉就没有了灵魂。 所以一直想把限流功能加上。 经查资料,实现功能如下:

限流功能配置

测试限流功能

具体实现如下:

代码语言:javascript
复制
@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及需求。 因为只有一个人,也欢迎大家参与进来.

网关系统暂时一段落,后面只修改缺陷不新增功能,主要是人不够,只有我一个人 其实网关还有很多我想做的。

  1. 协议泛化功能,将dubbo转http,将webservice转http
  2. 特定的日志查询与跟踪。需要将部分的日志做特殊处理,好做数据分析及跟踪
  3. 引入GraphQl,将普通的Rest接口转成GraphQl接口 可惜我一个人忙不过来 下期计划: 流程引擎(暂未开源) 1。增加机器人节点,可考虑做RPA的相关事情 2。优化流程图设计器,这方面涉及前端,不太擅长
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档