search
HomeDatabaseRedisHow to solve the timeout and oversold problems in the flash sale scenario in Redis

Timeout

1.Redis connection timeout reason

(1) Configuration issues in the virtual machine

When we test the remote connection to see whether the redis connection is successful, the console The following errors may be reported.
As shown below:

How to solve the timeout and oversold problems in the flash sale scenario in Redis

#I get a headache every time I see the red text on the console. . .

The display in the console probably means that the connection timeout caused the failure.
The following three reasons for connection failure are summarized:

  • The firewall in Linux is not closed and causes failure.

  • redis needs to be opened.

  • bind 127.0.01 in redis.conf needs to be commented out, and then protected-mode no needs to be modified.

If you encounter the above problems in the future, please look it up yourself.

(2) Simulate the timeout in high concurrency during redis successful connection

As shown in the figure:

How to solve the timeout and oversold problems in the flash sale scenario in Redis

2. Solution

You may find connection timeout problems when using jdbc in MySQL, so we use database connection pools to solve the problem, such as druid, c3p0, etc. In the same way, we can also use the database connection pool in redis.
Save the consumption caused by each connection to the redis service and reuse the connected instances.

Manage connection behavior through parameters

Go directly to the Notepad code!

How to solve the timeout and oversold problems in the flash sale scenario in Redis

Link pool parameters:

  • MaxTotal: Control how many jedis instances a pool can be allocated through pool.getResource() Obtain; if the value is -1, it means no limit; if the pool has been allocated MaxTotal jedis instances, the status of the pool at this time is exhausted.

  • maxIdle: Controls the maximum number of jedis instances in idle state in a pool;

  • MaxWaitMillis: Indicates when borrowing a jedis instance, the maximum number of milliseconds to wait. If the waiting time is exceeded, JedisConnectionException will be thrown directly;

  • testOnBorrow: Whether to check connection availability (ping()) when obtaining a jedis instance; if If true, the obtained jedis instances are all available;

Oversold

1. Flash kill oversold phenomenon

In high concurrency scenarios , multiple threads update the inventory concurrently, resulting in a negative inventory situation.

Look at pictures and imagine:

How to solve the timeout and oversold problems in the flash sale scenario in Redis

2. Solution

(1) Use optimistic locking to eliminate users and solve the overselling problem

Above picture:

How to solve the timeout and oversold problems in the flash sale scenario in Redis

//增加乐观锁
jedis.watch(qtkey);
 
//3.判断库存
String qtkeystr = jedis.get(qtkey);
if(qtkeystr==null || "".equals(qtkeystr.trim())) {
	System.out.println("未初始化库存");
	jedis.close();
	return false ;
}
 
int qt = Integer.parseInt(qtkeystr);
if(qt<=0) {
	System.err.println("已经秒光");
	jedis.close();
	return false;
}
 
//增加事务
Transaction multi = jedis.multi();
 
//4.减少库存
//jedis.decr(qtkey);
multi.decr(qtkey);
 
//5.加人
//jedis.sadd(usrkey, uid);
multi.sadd(usrkey, uid);
 
//执行事务
List<Object> list = multi.exec();
 
//判断事务提交是否失败
if(list==null || list.size()==0) {
	System.out.println("秒杀失败");
	jedis.close();
	return false;
}
System.err.println("秒杀成功");
jedis.close();	

How to solve the timeout and oversold problems in the flash sale scenario in Redis

How to solve the timeout and oversold problems in the flash sale scenario in Redis

##Principle of the scheme:

(1) When the user purchases, the inventory is monitored through watch. If the inventory changes after watch monitoring, the exception will be caught and the operation of decrementing the inventory by one will be given up.

(2) If no changes are monitored in the inventory and the quantity is greater than one, the inventory is reduced by one and the task is executed.
Disadvantages

When Redis tries to complete a transaction, it may repeatedly try to re-execute it due to the failure of the transaction

It is very important to ensure that the inventory of goods is correct, but simply Using a mechanism like WATCH puts too much pressure on the server

(2) Using the watch multi setnx command of reids to implement
Why do you need to build the lock yourself?

Although there are similar SETNX commands that can implement the lock function in Redis, the mechanism provided by other locks is not complete

And setnx does not have some advanced features of distributed locks, so we still have to pass it through Build manually.

(1) Create a redis lock

In Redis, you can build a lock by using the SETNX command: rs.setnx(lock_name, uuid value)

What the lock does It is to set a randomly generated 128-bit UUID to the value of the bit key to prevent the lock from being acquired by other processes.

(2) Release the lock

The deletion operation of the lock is very simple. You only need to judge and verify the uuid result obtained by the key value of the corresponding lock.

Meet the conditions (judge the uuid value) Just delete it in redis through delete, rs.delete(lockname)
In addition, when other users hold the same lock, due to the different uuid, other people's locks will not be released by mistake after verification.

(3) Solve the problem that the lock cannot be released

In the previous locks, there was also such a problem. For example, a process suddenly crashed after holding the lock, which would cause the lock to be unable to be released
and other processes could not hold the lock and continue working. In order to solve this problem Question, you can add the lock timeout function when acquiring the lock.

The above is the detailed content of How to solve the timeout and oversold problems in the flash sale scenario in Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis's Role: Exploring the Data Storage and Management CapabilitiesRedis's Role: Exploring the Data Storage and Management CapabilitiesApr 22, 2025 am 12:10 AM

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis: Understanding NoSQL ConceptsRedis: Understanding NoSQL ConceptsApr 21, 2025 am 12:04 AM

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

Redis: Real-World Use Cases and ExamplesRedis: Real-World Use Cases and ExamplesApr 20, 2025 am 12:06 AM

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

Redis: Exploring Its Features and FunctionalityRedis: Exploring Its Features and FunctionalityApr 19, 2025 am 12:04 AM

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

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.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.