search
HomeDatabaseRedisImplementation method of distributed current limiting mechanism of Redis

With the development of Internet applications, high concurrent access has become an extremely important issue for Internet companies. In order to ensure the stability of the system, we need to restrict access to prevent malicious attacks or excessive access from causing system crashes. Current limiting mechanisms are widely used in Internet applications. Redis, as a popular cache database, also provides distributed current limiting solutions.

The current limiting mechanism of Redis mainly has the following two implementation methods:

1. Current limiting based on the token bucket algorithm

The token bucket algorithm is a commonly used limitation method on the Internet. One of the streaming algorithms, Redis provides a current limiting solution based on the token bucket algorithm. The implementation of this solution is mainly based on Redis's ordered set (zset) and Lua script.

The principle of the token bucket algorithm is a fixed-capacity bucket, into which tokens are put at a certain rate. Each request needs to obtain a token from the bucket before it can be processed. If there is no token in the bucket, the request is rejected.

In Redis, we can use ordered sets (zset) to build token buckets. Each element in the ordered set represents a token, its score represents the arrival time of the token, and the value can be any value. Lua script is used to implement the operation of obtaining the token. The specific implementation code is as follows:

-- 获取令牌
local function acquire_token(key, rate, capacity, now)
  local current_capacity = redis.call("zcount", key, "-inf", "+inf")
  local delta_time = 1000 / rate
  local expected_token = math.floor((now - delta_time * capacity) / delta_time)
  local available_token = math.min(expected_token - current_capacity, capacity)
  if available_token > 0 then
    local members = {}
    for i = 1, available_token do
      members[i] = now
    end
    redis.call("zadd", key, unpack(members))
  end

  local current_time = now
  local stop_time = current_time + 1000
  local expire_time = stop_time - delta_time * (available_token - 1)
  local result = redis.call("zrangebyscore", key, "-inf", expire_time)
  if #result > 0 then
    redis.call("zrem", key, unpack(result))
    return 1
  end

  return 0
end

-- 调用获取令牌操作
local result = acquire_token(KEYS[1], ARGV[1], ARGV[2], ARGV[3])
return result

Among them, KEYS[1] represents the current-limiting Key, ARGV[1] represents the rate at which tokens are put in, ARGV[2] represents the bucket capacity, and ARGV[3] represents current time.

2. Current limiting based on funnel algorithm

The funnel algorithm is also a commonly used current limiting algorithm. Its principle is a funnel. Requests flow into the funnel like water. If the funnel is full , it will overflow. In Redis, we can also use ordered sets (zset) and Lua scripts to implement the funnel algorithm.

The funnel algorithm needs to maintain a funnel object to record the time of the last request and the current capacity of the bucket. When a new request comes, the algorithm will calculate the increase in capacity of the funnel based on the difference between the current time and the last request time. If the capacity is less than the maximum capacity of the bucket, the request is allowed to pass and the capacity is reduced; otherwise, the request is rejected.

The specific implementation code is as follows:

-- 获取令牌
local function acquire_token(key, rate, capacity, now)
  local current_capacity = redis.call("hget", key, "capacity")
  local last_time = redis.call("hget", key, "last_time")

  if current_capacity == redis.error_reply or current_capacity == ngx.null then
    current_capacity = capacity
    redis.call("hset", key, "capacity", current_capacity)
  else
    current_capacity = tonumber(current_capacity)
  end

  if last_time == redis.error_reply or last_time == ngx.null then
    last_time = now
    redis.call("hset", key, "last_time", last_time)
  else
    last_time = tonumber(last_time)
  end

  local delta_time = now - last_time
  local expected_capacity = delta_time * rate / 1000 + current_capacity
  local actual_capacity = math.min(expected_capacity, capacity)

  if actual_capacity >= 1 then
    redis.call("hset", key, "capacity", actual_capacity - 1)
    redis.call("hset", key, "last_time", now)
    return 1
  end

  return 0
end

-- 调用获取令牌操作
local result = acquire_token(KEYS[1], ARGV[1], ARGV[2], ARGV[3])
return result

Among them, KEYS[1] represents the current limiting Key, ARGV[1] represents the water adding rate of the funnel, ARGV[2] represents the capacity of the funnel, and ARGV [3] represents the current time.

Summary

The distributed current limiting mechanism provided by Redis can effectively control concurrent access and ensure the stability of the system. We can choose the token bucket algorithm or funnel algorithm as the current limiting algorithm according to business needs, and implement it through Redis's ordered set (zset) and Lua script. It should be noted that when applying the current limiting mechanism, the algorithm parameters should be reasonably configured based on specific business scenarios and traffic characteristics to avoid negative impacts on user experience.

The above is the detailed content of Implementation method of distributed current limiting mechanism of Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es和redis区别es和redis区别Jul 06, 2019 pm 01:45 PM

Redis是现在最热门的key-value数据库,Redis的最大特点是key-value存储所带来的简单和高性能;相较于MongoDB和Redis,晚一年发布的ES可能知名度要低一些,ES的特点是搜索,ES是围绕搜索设计的。

一起来聊聊Redis有什么优势和特点一起来聊聊Redis有什么优势和特点May 16, 2022 pm 06:04 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于redis的一些优势和特点,Redis 是一个开源的使用ANSI C语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式存储数据库,下面一起来看一下,希望对大家有帮助。

实例详解Redis Cluster集群收缩主从节点实例详解Redis Cluster集群收缩主从节点Apr 21, 2022 pm 06:23 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis Cluster集群收缩主从节点的相关问题,包括了Cluster集群收缩概念、将6390主节点从集群中收缩、验证数据迁移过程是否导致数据异常等,希望对大家有帮助。

Redis实现排行榜及相同积分按时间排序功能的实现Redis实现排行榜及相同积分按时间排序功能的实现Aug 22, 2022 pm 05:51 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,希望对大家有帮助。

详细解析Redis中命令的原子性详细解析Redis中命令的原子性Jun 01, 2022 am 11:58 AM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于原子操作中命令原子性的相关问题,包括了处理并发的方案、编程模型、多IO线程以及单命令的相关内容,下面一起看一下,希望对大家有帮助。

一文搞懂redis的bitmap一文搞懂redis的bitmapApr 27, 2022 pm 07:48 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了bitmap问题,Redis 为我们提供了位图这一数据结构,位图数据结构其实并不是一个全新的玩意,我们可以简单的认为就是个数组,只是里面的内容只能为0或1而已,希望对大家有帮助。

实例详解Redis实现排行榜及相同积分按时间排序功能的实现实例详解Redis实现排行榜及相同积分按时间排序功能的实现Aug 26, 2022 pm 02:09 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,下面一起来看一下,希望对大家有帮助。

redis error什么意思redis error什么意思Jun 17, 2019 am 11:07 AM

redis error就是redis数据库和其组合使用的部件出现错误,这个出现的错误有很多种,例如Redis被配置为保存数据库快照,但它不能持久化到硬盘,用来修改集合数据的命令不能用。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version