In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
Xiaobian to share with you Redis atomic counter incr to prevent concurrent requests refers to what, I hope you read this article after a big harvest, let us discuss it together!
I. Foreword
In some systems or features that limit high concurrency, such as spike activity, or some sites returning too many current users, try later. These limit the number of requests at the same time and are generally used to protect the background system from crashing due to excessive traffic impact. For the consequences of a system crash, it is obviously more acceptable for maintainers to reject some requests.
In all kinds of current limiting, except the counter with lock mechanism designed by the system itself, it is obviously an efficient, safe and convenient way to implement it by Redis.
II. INCR Command
The Redis Incr command increments the numeric value stored in key by one.
If the key does not exist, the value of the key is initialized to 0 before the INCR operation.
Returns an error if the value contains the wrong type, or if a value of string type cannot be represented as a number.
The value of this operation is limited to 64-bit signed digital representations.
Examples:
127.0.0.1:6379> set num 10OK127.0.0.1:6379> incr num(integer) 11127.0.0.1:6379> get num #Number value saved as string in Redis "11"
Note: Since redis does not have an explicit type to represent integer data, this operation is a string operation.
When this operation is performed, the string stored for the key is parsed into a 64-bit signed integer in base 10.
In fact, Redis internally uses integer representation to store the corresponding integer value, so the string value of this class is actually stored in integer, and there is no extra cost caused by storing the string representation of integer.
III. Use scenarios
1. counter
The idea is to send an incr command to the Redis server every time there is a related operation.
For example, let's say we have a web application and we want to keep track of how many times each user visits the site per day.
The web application simply concatenates the user id and a string representing the current time as a key, and executes incr on that key each time the user visits the page.
This scenario can be expanded in many ways:
By combining INCR and EXPIRE commands, you can implement a counter that records only the number of user visits within a specified interval
The client can retrieve the current counter value and reset it to 0 via the GETSET command
With atomic increment/decrement commands like DECR or INCRBY, certain values can be increased or decreased according to user actions. For example, online games require real-time control of user game scores, which can be increased or decreased.
2. speed limiter
A speed limiter is a special scenario that limits the rate at which certain operations can be performed.
A traditional example would be to limit the number of requests for a common api.
Suppose we want to solve the problem of limiting an api to no more than 10 requests per ip per second.
There are two ways to solve this problem using the incr command.
IV. Java implementation of flow control
Here we'll use the redis-incr feature in java to build a control code that only allows 100 requests per minute, where key represents the controlled key stored in redis.
public static boolean flowControl(String key){ //Maximum allowed 100 int max = 100; long total = 1L; try { if (jedisInstance.get(key) == null) { //jedisInstance is a Jedis connection instance, which can be obtained by single link or link pool. Please refer to the previous blog for implementation. //If redis doesn't have this key, create it and assign it 0, valid for 60s jedisInstance.setex(key, 60, "0"); } else { //get the value after adding 1 total = jedisInstance.incr(redisKey).longValue(); //Redis TTL returns the remaining expiration time of the key in seconds. When key does not exist, return-2. Returns-1 when key exists but the remaining lifetime is not set. Otherwise, return the remaining lifetime of the key in seconds. if (jedisInstance.ttl(redisKey).longValue() == -1L) { //Set the lifetime for a given key. When the key expires (lifetime = 0), it will be deleted automatically. jedisInstance.expire(redisKey, 60); } } } catch (Exception e) { logger.error("Flow control component: Failed to perform counting operation, unable to perform counting"); } long keytotaltransations = max; //Determine whether the maximum value has been exceeded, if it exceeds, return false if (total > keytotaltransations) { return false; } return true; } After reading this article, I believe you have a certain understanding of what Redis atomic counter incr prevents concurrent requests. If you want to know more about it, welcome to pay attention to the industry information channel. Thank you for reading!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.