Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the current limiting Strategy in Redis

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article will explain in detail how to realize the current-limiting strategy in Redis. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

1. Simple basic principle of current limitation

When the system processing capacity is limited, how to organize unplanned requests to put pressure on the system. First of all, let's take a look at some simple current restriction strategies to prevent violent attacks. For example, if you want to access IP, you can only visit 10 times in less than 5 seconds, which exceeds the interception.

As shown in the figure above, a sliding window is generally used to count the number of visits in an interval. Use zset to record the number of IP visits. Each IP is saved through key, score saves the current timestamp, and value is uniquely implemented with a timestamp or UUID.

The code implements public class RedisLimiterTest {private Jedis jedis; public RedisLimiterTest (Jedis jedis) {this.jedis = jedis } / * * @ param ipAddress Ip address * @ param period within a specified time, the maximum number of times per second * @ param maxCount * / public boolean isIpLimit (String ipAddress, int period, int maxCount) {String key = String.format ("ip:%s", ipAddress); / / millisecond timestamp long currentTimeMillis = System.currentTimeMillis () Pipeline pipe = jedis.pipelined (); / / redis transaction to guarantee atomicity pipe.multi (); / / store data, value and score both use millisecond timestamps pipe.zadd (key, currentTimeMillis, "" + UUID.randomUUID ()); / / remove all elements of the window interval pipe.zremrangeByScore (key, 0, currentTimeMillis-period * 1000) / / get the number of behaviors in the time window Response count = pipe.zcard (key); / / set the zset expiration time to prevent cold users from occupying memory continuously. Here allow 1s pipe.expire (key, period + 1); / / commit transaction pipe.exec (); pipe.close () / / compare whether the quantity exceeds the standard return count.get () > maxCount;} public static void main (String [] args) {Jedis jedis = new Jedis ("localhost", 6379); RedisLimiterTest limiter = new RedisLimiterTest (jedis); for (int I = 1; I this.capacity) {/ / the remaining space must not exceed the capacity this.leftQuota = this.capacity }} boolean watering (int quota) {makeSpace (); if (this.leftQuota > = quota) {/ / determine whether the remaining space is sufficient this.leftQuota-= quota; return true;} return false }} / / all funnel private Map funnels = new HashMap (); / * * @ param capacity funnel capacity * @ param leakingRate outlet flow rate quota/s * / public boolean isIpLimit (String ipAddress, int capacity, float leakingRate) {String key = String.format ("ip:%s", ipAddress); Funnel funnel = funnels.get (key) If (funnel = = null) {funnel = new Funnel (capacity, leakingRate); funnels.put (key, funnel);} return! funnel.watering (1); / / 1 quota} public static void main (String [] args) throws Exception {FunnelLimiterTest limiter = new FunnelLimiterTest (); for (int I = 1; I cl.throttle key:xxx 15 30 60 1)

15: 15 capacity this is the funnel capacity.

30 60: 30 operations / 60 seconds this is the leakage rate

1: need 1 quota (optional parameter, default is also 1)

> cl.throttle laoqian:reply 15 30 601) (integer) 0 # 0 means allow, 1 means reject 2) (integer) 15 # funnel capacity capacity3) (integer) 14 # funnel remaining space left_quota4) (integer)-1 # if rejected, how long will it take to try again (funnel has space, unit second) 5) (integer) 2 # after more than a long time, the funnel is completely empty (left_quota==capacity, unit second)

When executing a current-limiting instruction, if it is rejected, it needs to be discarded or retried. The cl.throttle instruction is so thoughtful that even the retry time can be calculated for you. You can directly take the fourth value of the returned result array for sleep. If you do not want to block the thread, you can also retry the task asynchronously.

This is the end of the article on "how to realize the current-limiting strategy in Redis". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report