In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how the Redis atomic counter incr prevents concurrent requests. 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.
I. Preface
In some systems or features that are limited to high concurrent requests, such as flash sale activity, or some websites return too many current users, please try later. These are by limiting the number of requests at the same time, which are generally used to protect the background system to prevent the system from crashing due to excessive traffic impact. For the consequences of a system crash, it is clear that rejecting some requests is more acceptable to maintainers.
In all kinds of current limit, in addition to the counter with locking mechanism designed by the system itself, it is obviously an efficient, safe, convenient and convenient way to use Redis.
II. Incr command
The Redis Incr command increments the numeric value stored in key by one.
If key does not exist, the value of key is initialized to 0 before performing the INCR operation.
If the value contains the wrong type, or if the value of the string type cannot be represented as a number, an error is returned.
The value of this operation is limited to a 64-bit (bit) signed numeric representation.
Example:
127.0.0.1 set num 10OK127.0.0.1:6379 > incr num (integer) 11127.0.1 integer > get num # numeric values are saved as strings in Redis "11"
Note: since redis does not have an explicit type to represent integer data, this operation is a string operation.
When you do this, the string stored by the key is parsed into 64-bit signed integer data in decimal.
In fact, the corresponding integer values are stored internally in Redis in the form of integers (Integer representation), so this kind of string values are actually stored in integers, so there is no extra consumption caused by the string representation (String representation) of storing integers.
Third, use the scene
1. Counter
The idea is to send an incr command to the Redis server every time there is a related operation.
For example, in a scenario like this: we have a web application, and we want to record the number of times each user visits the site every day.
The web application only needs to concatenate the user id and the string representing the current time as the key, and execute the incr command on the key each time the user visits the page.
There are many ways to extend this scenario:
By using the INCR and EXPIRE commands together, you can implement a counter that only records the number of visits made by the user within a specified interval.
The client can get the value of the current counter and reset it to 0 through the GETSET command
Through atomic increment / decrement commands such as DECR or INCRBY, you can increase or decrease certain values according to the user's actions, such as online games, which require real-time control of the user's game score, which may increase or decrease.
two。 Speed limiter
The speed limiter is a special scenario in which the speed of some operations can be limited.
The traditional example is to limit the number of requests for a public api.
Suppose we want to solve the following problem: limit the number of requests per ip per second for an api to no more than 10.
We can use the incr command to implement two ways to solve this problem.
Fourth, the java realization of flow control.
Here we will use the features of redis-incr in java to build a control code that allows only 100 requests in a minute. Key represents the controlled key value stored in the redis.
Public static boolean flowControl (String key) {/ / maximum allowable 100 int max = 100; long total = 1L Try {if (jedisInstance.get (key) = = null) {/ / jedisInstance is a Jedis connection instance, which can also be obtained by using link pooling. For implementation, please refer to the previous blog content / / if redis does not currently have this key, create and assign 0 with a validity time of 60s jedisInstance.setex (key, 60, "0") } else {/ / gets the value total = jedisInstance.incr (redisKey). LongValue (); / / the Redis TTL command returns the remaining expiration time of key in seconds. Returns-2 when key does not exist. Returns-1 when key exists but the remaining time to live is not set. Otherwise, the remaining lifetime of the key is returned in seconds. If (jedisInstance.ttl (redisKey). LongValue () =-1L) {/ / sets the time to live for a given key, which is automatically deleted when the key expires (time to live is 0). JedisInstance.expire (redisKey, 60);} catch (Exception e) {logger.error ("flow control component: failed to perform count operation, unable to count");} long keytotaltransations = max; / / to determine whether the maximum value has been exceeded, and return false if (total > keytotaltransations) {return false if it exceeds } return true;} about the Redis atomic counter incr how to prevent concurrent requests to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can 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.
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.