1. 程式人生 > >redis使用watch秒殺搶購思路

redis使用watch秒殺搶購思路

fixed shutdown author pub 邏輯 uid trace sets ren

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

測試代碼:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import redis.clients.jedis.Jedis;

/**
 * redis測試搶購
 * 
 * @author 10255_000
 * 
 */
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");// 重置watchkeys為0
        jedis.del("setsucc", "setfail");// 清空搶成功的,與沒有成功的
        jedis.close();

        for (int i = 0; i < 10000; i++) {// 測試一萬人同時訪問
            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";// 監視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();// 開啟事務

                tx.incr("watchkeys");

                List<Object> list = tx.exec();// 提交事務,如果此時watchkeys被改動了,則返回null
                if (list != null) {
                    System.out.println("用戶:" + userifo + "搶購成功,當前搶購成功人數:"
                            + (valint + 1));
                    /* 搶購成功業務邏輯 */
                    jedis.sadd("setsucc", userifo);
                } else {
                    System.out.println("用戶:" + userifo + "搶購失敗");
                    /* 搶購失敗業務邏輯 */
                    jedis.sadd("setfail", userifo);
                }

            } else {
                System.out.println("用戶:" + userifo + "搶購失敗");
                jedis.sadd("setfail", userifo);
                // Thread.sleep(500);
                return;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }

    }

}

redis使用watch秒殺搶購思路