1. 程式人生 > >redis使用事物

redis使用事物

package domain;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 秒殺
 */
public class SecKill {

    public static String KEY = "kill";

    public static void main(String args[]) {

        ExecutorService service = Executors.newFixedThreadPool(20);

        Jedis jedis = new Jedis("192.168.0.21", 6379, 1000);

        jedis.set(SecKill.KEY, "100");
        jedis.close();

        for (int i = 0; i < 10000; i++) {
            service.execute(new MyRunnable("secKill:"+i));
        }

        service.shutdown();
    }
}

class MyRunnable implements Runnable {

    private String userName;
    private Jedis jedis = new Jedis("192.168.0.21", 6379, 1000);

    public MyRunnable(String userName) {
        this.userName = userName;
    }

    @Override
    public void run() {
        //建立監聽
        jedis.watch(SecKill.KEY);
        //對物品數量檢測
        String num = jedis.get(SecKill.KEY);
        if (Integer.parseInt(num) > 0) {
            //獲取事務
            Transaction tx = jedis.multi();
            //執行邏輯
            tx.incrBy(SecKill.KEY, -1);
            //提交事務
            List<Object> result = tx.exec();
            //執行事後邏輯
            if (null == result) {
                //System.out.println("搶購失敗,物品剩餘資源不足,使用者id:" + userName);
                jedis.close();
                return;
            }

            if (result.size() == 0) {
                //System.out.println("搶購失敗,物品剩餘" + num + ",使用者id:" + userName);
                jedis.close();
                return;
            }

            if (result.size() > 0) {
                System.out.println("搶購成功,物品剩餘" + result.get(0) + ",使用者id:" + userName);
            }
        }
        //關閉資源
        jedis.close();
    }
}