search
HomeDatabaseRedisParse incr and hash applications of redis

incr

For example, Beijing license plates adopt a process of grabbing first and then approving the qualifications. There are N numbers in the license plate pool, and the page is displayed in ten items per page. There is a grab button after each number, and one person can only grab one license plate, and the same license plate can only be grabbed by one person. Business model reference (http://num.10010.com/NumApp/chseNumList/init?num=186)

 if ($this->redis_db->incr("bj_".$car_no) != 1) {
      让别人先下手了,点别的去~
  }else{
       //抢到竞态条件,如果不复核资质要求退出,并清除incr
       if(抢到了但是没资质等){
         释放对此id的竟态权,别占茅坑
         $this->yredis_db->del("bj_".$id);
       }else{
         其他业务A
         抱得号码归...
         其他业务B
     }
}

In addition,incrCan be operated on string type, hash type, sortedSet type

blpop

blpopOne advantage over lpop is that it can perform priority operations on multiple queues.
blpop will pop up in sequence according to the order of key. The return value is the listname and specific element value of key, and block# can be set. ## Time, the principle is to block first and serve first.

        $date = date('Ymd', time());
        //左进左出 ,优先分配一般的车牌号码,然后在分配非常好的连号号码,设置一个阻塞时间
        return $this->redis->blpop(self::$_config['dispatch_normal_list'] . $date, self::$_config['dispatch_better_list'] . $date, self::$_config['redis_block_l_pop_time_out']);
hsetnx

Set a

field in hash to the specified value, provided that field does not exist. If present, returns 0. This ensures that one person can only grab one license plate, but during the process of grabbing the license plate to perform payment or other business operations, other people cannot do this (that is, this license plate cannot be bound to other people). Depending on the specific business situation, a hash field based on car_no and a hash field based on people can be set.

hash_base_people {"zhangsan":"京A888","lisi":"京A999"}
hash_base_car_no {"京A888":"zhangsan","京A999":"lisi"}
Based on these two hashes, you can do more business-related operations, such as checking the specific binding relationship through hget, etc.

hdel

With the binding model through hsetnx, when someone pays a deposit for a certain license plate, etc., it means that it can be eliminated forever. This will be used hdel. In addition, if no operations such as paying a deposit are performed within the specified time, the license plate number will be returned to the original list.

 //删除以people_id为key的hash
 $base_people_id_del = $this->redis->hdel(self::$_config['hash_base_people'], $people_id);

 //删除以car_no为key的hash
 $base_car_no_del = $this->redis->hdel(self::$_config['hash_base_car_no'], $clue_id);
lpush

If there is an entrance, put the license plates that can be snapped in Beijing into a list

$lpush_res = $redisObj->lpush($list_name, $car_no);
The value of list_name can be determined according to the specific value of car_no. For example, if there are 6 and 8, I will put them in the

better_car_no list, and the others in the normal_car_no list. Finally, I can use blpop to specify a sequence. priority.

rpoplpush

Safe queue pop-up mode, for example, N multiple people operate an entrance button. If there is enough data in the list structure, each person will have and only one piece of data will be received. Do other business operations after receiving it.

But the problem is that after using
lpop, the original queue has been popped. If the client obtains the pop element in the middle and before completing the processing of this element, The client crashed. At this time, the message disappeared out of thin air. If there are no other supplementary measures (such as binding or recording the pop-up element) that require strict requirements, you can use rpoplpush to solve this problem. After the client actually processes the pop element, this message is safely deleted through lrem.

Recommended study: "

redis video tutorial"

The above is the detailed content of Parse incr and hash applications of redis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Is Redis a SQL or NoSQL Database? The Answer ExplainedIs Redis a SQL or NoSQL Database? The Answer ExplainedApr 18, 2025 am 12:11 AM

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis: Improving Application Performance and ScalabilityRedis: Improving Application Performance and ScalabilityApr 17, 2025 am 12:16 AM

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis: Exploring Its Data Model and StructureRedis: Exploring Its Data Model and StructureApr 16, 2025 am 12:09 AM

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis: Classifying Its Database ApproachRedis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AM

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Why Use Redis? Benefits and AdvantagesWhy Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AM

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Understanding NoSQL: Key Features of RedisUnderstanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AM

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

Redis: Identifying Its Primary FunctionRedis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AM

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis: A Guide to Popular Data StructuresRedis: A Guide to Popular Data StructuresApr 11, 2025 am 12:04 AM

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor