How to realize flash sale scenario of inventory reduction through redis
The main purpose of Redis inventory reduction is to reduce access to the database. The previous inventory reduction directly accessed the database and read the inventory. When high concurrent requests come, a large amount of read data may cause the database to collapse.
Usage ideas:
When the system is initialized, the product inventory is loaded into the Redis cache and saved.
When receiving the request, first get the inventory value of the product in Redis and pre-reduce the inventory. If the inventory is insufficient after the reduction, a logical Exception will be returned directly without access. The database will then reduce the inventory. If the inventory value is correct, proceed to the next step.
Enqueue the request and immediately return a value to the front end, indicating that it is being queued, and then perform the flash killing logic. The backend queue performs the flash killing logic, and the front end polls the requests sent by the back end. , if the flash kill is successful, return the flash kill, success, otherwise it will return failure.
The first step: After the system is initialized, put all product inventory into the cache
/** * 秒杀接口优化之--- 第一步: 系统初始化后就将所有商品库存放入 缓存 */ @Override public void afterPropertiesSet() throws Exception { List<GoodsVo> goods = goodsService.getGoodsList(); if (goods == null) { return; } for (GoodsVo goodsVo : goods) { redisService.set(GoodsKey.getId(), goodsVo.getStockCount()); isOverMap.put(goodsVo.getId(), false);//先初始化 每个商品都是false 就是还有 } }
The second step: Pre-reduction inventory is reduced from the cache
/**秒杀接口优化之 ----第二步: 预减库存 从缓存中减库存 * 利用 redis 中的方法,减去库存,返回值为 减去1 之后的值 * */ long stock = redisService.decr(GoodsKey.getGoodsStock, "" + goodsId); /*这里判断不能小于等于,因为减去之后等于 说明还有是正常范围*/ if (stock < 0) { isOverMap.put(goodsId, true);//没有库存就设置 对应id 商品的map 为true return Result.error(CodeMsg.MIAO_SHA_NO_STOCK); }
The overall logic is as follows:
1. First read out all the data, initialize it into the cache, and store it in Redis in the form of stock goodid.
2. During the flash sale, first perform pre-reduction inventory detection, and use decr to subtract the inventory of the corresponding product from redis. If the inventory is less than 0, it means that the inventory is insufficient at this time, and there is no need to access the database. Just throw an exception directly.
We also used isOverMap above, which is a memory mark.
Memory mark
Due to interface optimization, many cache operations based on Redis will also bring a great burden to the Redis server when the concurrency is high. If the load on the Redis server can be reduced, Access can also achieve the optimization effect.
So, you can add a memory map to mark whether the inventory of the corresponding product is still there. Before accessing Redis, you can get the inventory mark of the corresponding product in the map, and you can judge without accessing Redis. out of stock.
1. Generate a map, and during initialization, use the ids of all products as keys and mark false to store them in the map.
private Map<Long, Boolean> isOverMap = new HashMap<Long, Boolean>(); /** * 秒杀接口优化之--- 第一步: 系统初始化后就将所有商品库存放入 缓存 */ @Override public void afterPropertiesSet() throws Exception { List<GoodsVo> goods = goodsService.getGoodsList(); if (goods == null) { return; } for (GoodsVo goodsVo : goods) { redisService.set(GoodsKey.getGoodsStock, "" + goodsVo.getId(), goodsVo.getStockCount()); isOverMap.put(goodsVo.getId(), false);//先初始化 每个商品都是false 就是还有 } }
/**再优化: 优化 库存之后的请求不访问redis 通过判断 对应 map 的值 * */ boolean isOver = isOverMap.get(goodsId); if (isOver) { return Result.error(CodeMsg.MIAO_SHA_NO_STOCK); } if (stock < 0) { isOverMap.put(goodsId, true);//没有库存就设置 对应id 商品的map 为true }
2. Before pre-reducing inventory, get the mark from the map. If the mark is false, it means the inventory
When the inventory is insufficient, reduce the product inventory in advance and mark it as true. Indicates that the product is out of stock. All requests below will be intercepted, and there is no need to access redis for pre-stock reduction.
So the overall idea of using cache is as follows:
Load the inventory data of the product into the memory, and initialize the memory tag at the same time, that is, store the id of each product in the map, which is initialized to false , before each flash sale logic needs to be executed, the value is obtained in the memory mark. If there is still stock, that is, the return value in the map is false, the flash sale logic will be executed, otherwise an exception will be thrown directly.
When deducting inventory at the same time, you need to determine whether the inventory quantity in the cache is still greater than 0. If it is less than or equal to 0, modify the memory mark.
The above is the detailed content of How to realize flash sale scenario of inventory reduction through redis. 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.
