redis使用watch秒殺搶購思路

1、使用watch,採用樂觀鎖 
2、不使用悲觀鎖,因爲等待時間非常長,響應慢 
3、不使用隊列,因爲併發量會讓隊列內存瞬間升高

package com.javartisan.concurrent;
 
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.List;
import java.util.UUID;
 
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;
 
/**
 * redis併發搶購測試
 *
 * @author javartisan
 */
public class RedisTest {
    public static void main(String[] args) {
        final String watchkeys = "watchkeys";
        ExecutorService executor = Executors.newFixedThreadPool(20);
 
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
 
        JedisPool jedisPool = new JedisPool(poolConfig, "127.0.0.1", 6379, 10000, "root");
 
 
        final Jedis jedis = jedisPool.getResource();
        jedis.auth("root");
        jedis.set(watchkeys, "0");// 重置watchkeys爲0
        jedis.del("setsucc", "setfail");// 清空搶成功的,與沒有成功的
        jedis.close();
 
        for (int i = 0; i < 10000; i++) {// 測試一萬人同時訪問
            executor.execute(new MyRunnable(jedisPool));
        }
        executor.shutdown();
    }
}
 
 
class MyRunnable implements Runnable {
 
    String watchkeys = "watchkeys";// 監視keys
    JedisPool jedisPool = null;
 
 
    public MyRunnable(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }
 
    @Override
    public void run() {
        Jedis jedis = jedisPool.getResource();
 
        try {
 
            <strong>jedis.watch(watchkeys);//代碼塊1 watchkeys</strong>
 
            String val = jedis.get(watchkeys);
            int valint = Integer.valueOf(val);
            String userifo = UUID.randomUUID().toString();
            if (valint < 10) {
 
                <strong>Transaction tx = jedis.multi();//代碼塊2 開啓事務
                tx.incr("watchkeys");
                List<Object> list = tx.exec();//代碼塊3 提交事務,如果此時watchkeys被改動了,則返回emptyList</strong>
 
                if (list.size() > 0) {
                    System.out.println("用戶:" + userifo + "搶購成功,當前搶購成功人數:" + (valint + 1));
                    /* 搶購成功業務邏輯 */
                    jedis.sadd("setsucc", userifo);
                    return;
                }
            }
            System.out.println("用戶:" + userifo + "搶購失敗");
            jedis.sadd("setfail", userifo);
            return;
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
 
 
    }
 
}

 

Redis對事物的支持目前比較簡單。Redis只能保證一個client發起的事務中的命令可以連續的執行,但後面命令出錯前面不會回滾。而中間不會插入其他client的命令。當一個client在找一個連續中發出multi命令時,這個鏈接會進入一個事務上下文,該鏈接後續的命令不會立即執行,而是先放到隊列中,當執行exec命令是,redis會順序的執行隊列中的所有命令。當如果隊列中有命令錯誤,不會回滾。

樂觀鎖:大多數是基於數據版本(version)的記錄機制實現的。即爲數據增加一個版本標識,在基於數據庫表的版本解決方案中,一般是通過爲數據庫表添加一個”version”字段來實現讀取出數據時,將此版本號一同讀出,之後更新時,對此版本號+1。此時,將提交數據的版本號與數據庫表對應記錄版本號進行比對,如果提交的數據版本號大於數據當前版本號,則予以更新,否則認爲是過去數據。

在Redis中,使用watch命令實現樂觀鎖(watch key): 
watch命令會監視給定的key,當exec時,如果監視的key從調用watch後發生過變化,則事務會失敗,也可以調用wathc多長監視多個key。這樣就可以對指定key加樂觀鎖了。注意watch的可以是對整個連接有效的。事務也一樣。如果連接斷開,監視和事務都會被自動清除。當然exec,discard,unwatch命令都會清除連接中的所有監視。

 

Jedis中的exec方法實現源碼:

public List<Object> exec() {
   client.exec();
   client.getAll(1); // Discard all but the last reply
   inTransaction = false;
 
   <strong>List<Object> unformatted = client.getObjectMultiBulkReply();</strong>
 <strong>  if (unformatted == null) { //事務失敗
     return Collections.emptyList();
   }</strong>
   List<Object> formatted = new ArrayList<Object>();
   for (Object o : unformatted) {
     try {
       formatted.add(generateResponse(o).get());
     } catch (JedisDataException e) {
       formatted.add(e);
     }
   }
   return formatted;
 }

 

https://www.cnblogs.com/leodaxin/p/9553988.html

https://blog.csdn.net/qq1013598664/article/details/70183908

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章