Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use watch in redis to realize a second-kill panic buying function

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

How to use watch in redis to achieve a second-kill panic buying function? In view of this problem, this article introduces the corresponding analysis and answers in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

The details are as follows

1. Use watch and adopt optimistic lock

2. Do not use pessimistic lock because the waiting time is very long and the response is slow.

3. Do not use queues, because the concurrency will instantly increase the queue memory.

Code:

Import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import redis.clients.jedis.Jedis;/** * redis Test snap up * * @ author 10255000000 * * / public class RedisTest {public static void main (String [] args) {final String watchkeys = "watchkeys"; ExecutorService executor = Executors.newFixedThreadPool (20); final Jedis jedis = new Jedis ("192.168.3.202", 6379); jedis.set (watchkeys, "0") / / reset watchkeys to 0 jedis.del ("setsucc", "setfail"); / / clear the successful and unsuccessful jedis.close (); for (int I = 0; I < 10000; iTunes +) {/ / Test 10,000 simultaneous visits to executor.execute (new MyRunnable ();} executor.shutdown ();}} import java.util.List;import java.util.UUID;import redis.clients.jedis.Jedis;import redis.clients.jedis.Transaction Public class MyRunnable implements Runnable {String watchkeys = "watchkeys"; / / Monitoring keys Jedis jedis = new Jedis ("192.168.3.202", 6379); public MyRunnable () {} @ Override public void run () {try {jedis.watch (watchkeys); / / watchkeys String val = jedis.get (watchkeys); int valint = Integer.valueOf (val); String userifo = UUID.randomUUID (). ToString (); if (valint < 10) {Transaction tx = jedis.multi () / / start the transaction tx.incr ("watchkeys"); List list = tx.exec (); / / commit the transaction. If the watchkeys is changed, return null if (list! = null) {System.out.println ("user:" + userifo + "snapped up successfully, the current number of snapped-up successes:" + (valint + 1) / * panic purchase success business logic * / jedis.sadd ("setsucc", userifo);} else {System.out.println ("user:" + userifo + "panic purchase failure"); / * panic purchase failure business logic * / jedis.sadd ("setfail", userifo);}} else {System.out.println ("user:" + userifo + "panic purchase failure") Jedis.sadd ("setfail", userifo); / / Thread.sleep (500); return;}} catch (Exception e) {e.printStackTrace ();} finally {jedis.close ();}

Redis's support for things is relatively simple right now. Redis can only guarantee that commands in an client-initiated transaction can be executed continuously, but the subsequent commands will not be rolled back before they go wrong. No other client commands are inserted in the middle. When a client is looking for a continuous multi command, the link enters a transaction context, and the subsequent commands of the link are not executed immediately, but are first placed in the queue. When the exec command is executed, redis executes all the commands in the queue sequentially. If there is a command error in the queue, it will not be rolled back.

Optimistic locking: most are implemented based on the data version (version) recording mechanism. That is, to add a version identification to the data, in the version solution based on the database table, it is generally achieved by adding a "version" field to the database table to read out the data, the version number is read out together, and then updated, the version number is + 1. At this point, the version number of the submitted data is compared with the corresponding record version number of the database table, and if the submitted data version number is greater than the current version number of the data, it will be updated, otherwise it is considered to be past data.

In Redis, use the watch command to implement optimistic locking (watch key):

The watch command monitors a given key, and when exec, if the monitored key has changed since the call to watch, the transaction will fail, or you can call wathc to monitor multiple key. This allows you to add an optimistic lock to the specified key. Note that watch can be valid for the entire connection. It's the same with business. If the connection is disconnected, both monitoring and transactions are automatically cleared. Of course, the exec,discard,unwatch command clears all monitoring from the connection.

This is the answer to the question about how to use watch in redis to achieve a second-kill panic buying function. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report