订单扣减库存,Redis实现限流算法

/**
 * 乐观锁更新 + 限流
 *
 * @param sid
 */
@RequestMapping(value = "createOptimisticLimitOrder", method = RequestMethod.POST)
@ResponseBody
public String createOptimisticLimitOrder(HttpServletRequest request, int sid) {
    int res = 0;
    try {
        if (RedisLimit.limit()) {
            res = orderService.createOptimisticOrder(sid);
        }
    } catch (Exception e) {
        log.error("Exception: " + e);
    }
    return res == 1 ? success : error;
}
/**
 * Redis 限流
 */
public static Boolean limit() {
    Jedis jedis = null;
    Object result = null;
    try {
        // 获取 jedis 实例
        jedis = RedisPool.getJedis();
        // 解析 Lua 文件
        String script = ScriptUtil.getScript("limit.lua");
        // 请求限流
        String key = String.valueOf(System.currentTimeMillis() / 1000);
        // 计数限流
        result = jedis.eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit)));
        if (FAIL_CODE != (Long) result) {
            log.info("成功获取令牌");
            return true;
        }
    } catch (Exception e) {
        log.error("limit 获取 Jedis 实例失败:", e);
    } finally {
        RedisPool.jedisPoolClose(jedis);
    }
    return false;
}

-- 计数限流
-- 每次请求都将当前时间,精确到秒作为 key 放入 Redis 中,超时时间设置为 2s, Redis 将该 key 的值进行自增
-- 当达到阈值时返回错误,表示请求被限流
-- 写入 Redis 的操作用 Lua 脚本来完成,利用 Redis 的单线程机制可以保证每个 Redis 请求的原子性

-- 资源唯一标志位
local key = KEYS[1]
-- 限流大小
local limit = tonumber(ARGV[1])

-- 获取当前流量大小
local currentLimit = tonumber(redis.call('get', key) or "0")

if currentLimit + 1 > limit then
    -- 达到限流大小 返回
    return 0;
else
    -- 没有达到阈值 value + 1
    redis.call("INCRBY", key, 1)
    -- 设置过期时间
    redis.call("EXPIRE", key, 2)
    return currentLimit + 1
end

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值