How to use Redis for scheduled inventory caching function
1. Business background
I decided to compare this question to the questions on the exam paper to avoid introducing the background of our company's projects. As for the details of the business, you don’t need to pay attention to it~ Just read the title:
Suppose you are the best collector in a certain country, and you have various treasures with continuous value in your hands. One day you may feel that your collection is getting boring and decide to sell these valuable items for cash.
But it is too low to sell these valuable treasures in the vegetable market. In the "Internet" era, of course we have to play some different selling methods: there is a 300-room building (numbered 001 to 300) in your name, and each room has a password-locked safe. In the next month ( Every day from December 1st to December 31st), you will select 300 of the best "top treasures" (also called Class A treasures) and put them in the safes of these 300 rooms, each room every day The treasures to be placed have already been decided. Anyone who wants to buy treasures must make a reservation online at least one day in advance, and then use the reservation code to open the safe and pick up the goods. Treasures that are not reserved will be taken back by you and will no longer be sold.
To build such an online reservation system, its front-end interface may look like this:
Click on the three controls to be filled in in the picture above. A selection box will appear. The problem now is that there is only one treasure in a room and it cannot be booked twice. After the buyer selects the treasure type and room number, it is recommended to provide some prompt information in the date selection box when they select the reservation date. For example, room No. 051 has been booked on December 3, and now another user has selected room No. 051. Then when the date selection box pops up, December 3 must be set as unselectable. As shown below (December 3rd is displayed as "missing"):
So, how can such a simple inventory system be stored in redis?
2. Inventory Management Solution (Redis)
Our initial idea is that our inventory can be regarded as a huge three-dimensional array, where the first dimension represents the treasure type, and the second dimension The first dimension represents the room number, and the third dimension represents the reservation date. Redis provides five storage types: String, Hash, List, Set, and Sorted Set. We can use the Hash type to store data in the current scenario because it can meet our needs, and the Set type is also a feasible option.
The key of Redis is set to the treasure type room number (for example, A:205, A represents the best treasure, 205 is the room number), the value of Redis is the hash type, and the hash key is the date (for example, 2016-12-05 ), the hash value is true or false, indicating that it has been booked or not. The graphic representation is:
If Room 158 of Category A treasure has been booked on December 8, it will be stored as
1 2 3 |
##Redis Key —— A:158 Redis Value —— hash table [ |
1 2 3 |
|
For B-type treasures, when making new reservations, you need to take out the original hash value first, do logical OR operation with the new scheduled pickup time, and then write the result back to Redis, instead of doing the same thing as Like Class A treasures, hSet is directly called to set the hash value; when canceling the reservation, pay attention to taking out the original hash value first, deducting the time period to be canceled from the hash value (XOR logical AND operation), and then re-setting the hash value. The remaining reserved pickup times are written back to Redis and cannot be deleted directly by calling hDel.
4. Advanced & Inventory Management Plan
Since the launch of Class B treasures, your business has become much more popular than before. So new demand has come again. Now there are a large number of tourists, students and other people without huge savings who are very interested in your treasures. People who come to this city want to bring some souvenirs back. Although the price of type B treasures is slightly lower than that of type A, it is still a bit expensive for these people. So, you decide to sell your most affordable treasures (Category C treasures).
Among these 300 rooms, Type C treasures store the largest number, so you add 100 treasure boxes specifically for storing Type C treasures in each room. These 100 treasure boxes are numbered No. 1, No. 2,..., No. 100. Similarly, every hour of the day, you will put a C-type treasure into the 100 treasure boxes in each of these 300 rooms (which means that the entire building will update 30,000 C-type treasures every hour). pieces). If no one makes a reservation, the treasure will be replaced the next hour. Finally, everyone's needs can be met.
For C-type treasures, your reservation interface will look like this:
We have added another reservation condition. At this time, we are faced with the problem of inventory storage. As usual, this inventory is actually a large five-dimensional array. The treasure type, room number, reservation date, pickup time, and treasure box number each occupy one dimension. We have used up all the capacities of Redis before. What should we do now to store data?
This time the Redis inventory storage must be combined with business characteristics. First of all, the two dimensions of treasure chest number and pickup time do not have too many value ranges. There are only 100 treasure chest numbers. Just change the hash value into an array with a length of 100, and each position of the array contains INT. The pickup time indicated by the type is sufficient. However, the hash value can only be string... So, we have to do an array serialization operation, and then deserialize it back when reading. Fortunately, the length is only 100, so serialization efficiency will not become the bottleneck of the system.
The storage method is: On December 23rd and 24th, among the C-type treasures in Room 258, the treasure chests numbered 97 and 99 have been reserved between 11 am and 1 pm
1 2 3 |
##Redis Key —— C :258 Redis Value —— hash table [ |
The above is the detailed content of How to use Redis for scheduled inventory caching function. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

Redis, as a message middleware, supports production-consumption models, can persist messages and ensure reliable delivery. Using Redis as the message middleware enables low latency, reliable and scalable messaging.
