Home  >  Article  >  Database  >  redis auto-increment count

redis auto-increment count

尚
Original
2020-05-08 09:29:185266browse

redis auto-increment count

INCR key

Increase the numerical value stored in key by one.

If key does not exist, the value of key will be initialized to 0 first, and then the INCR operation will be performed.

If the value contains the wrong type, or a string type value cannot be represented as a number, then an error is returned.

The value of this operation is limited to 64-bit (bit) signed digital representation.

This is an operation for strings. Because Redis does not have a dedicated integer type, the string stored in the key is interpreted as a decimal 64-bit signed integer to perform the INCR operation.

Available versions:

>= 1.0.0

Time complexity:

O(1)

Return value:

The value of key after executing the INCR command.

redis> SET page_view 20
OK
redis> INCR page_view
(integer) 21
redis> GET page_view    # 数字值在 Redis 中以字符串的形式保存
"21"

The counter is the most intuitive mode that Redis's atomic self-increment operation can implement. Its idea is quite simple: whenever an operation occurs, send an INCR command to Redis.

For example, in a web application, if you want to know the number of user clicks every day for a year, then you only need to use the user ID and related date information as keys, and execute it every time the user clicks on the page. One auto-increment operation is enough.

For example, if the user name is peter and the click time is March 22, 2012, then execute the command INCR peter::2012.3.22.

This simple pattern can be extended in the following ways:

  • You can use INCR and EXPIRE in combination to achieve counting only within the specified survival time ( counting) purpose.

  • The client can atomically obtain the current value of the counter and clear the counter by using the GETSET command. For more information, please refer to the GETSET command.

  • Using other increment/decrement operations, such as DECR and INCRBY, users can increase or decrease the value of the counter by performing different operations, such as scorers in games. to these commands.

For more redis knowledge, please pay attention to the redis introductory tutorial column.

The above is the detailed content of redis auto-increment count. 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