Java操作Redis事務


package com.example.redis.other;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

public class TestTransaction {
    public static void main(String[] args) throws InterruptedException {
        boolean isSuccess = isSuccess("balance", "debt", 20l);
        System.out.println("main retVal-------"+isSuccess);
    }



    public static boolean isSuccess(String balance,String debt,Long delAmount) throws InterruptedException {
        Jedis jedis = new Jedis("127.0.0.1",6379);
     // Watch 命令用於監視一個(或多個) key ,如果在事務執行之前這個(或這些) key 被其他命令所改動,那么事務將被打斷 jedis.watch(balance); Long amount
= Long.parseLong(jedis.get(balance)); Long debts = Long.parseLong(jedis.get(debt)); if(amount<delAmount){
       //Redis Unwatch 命令用於取消 WATCH 命令對所有 key 的監視。 jedis.unwatch(); System.out.println(
"amount can't Less than delAmount !!!!"); return false; } {
       //Redis 通過 MULTI 開始一個事務, 然后將多個命令入隊到事務中, 最后由 EXEC 命令觸發事務 Transaction transaction
= jedis.multi(); transaction.decrBy(balance, delAmount); transaction.incrBy(debt,delAmount); //在這里模擬網絡延遲時,我們通過redis命令窗口手動去修改balance值。
        
            Thread.sleep(3000);
            List<Object> exec = transaction.exec();
            //執行exec操作時發現balance值被修改,因此終止操作。
            if(exec.size()<=0){
                System.out.println("balance is upfated by other person,debt is fail!!!");
                return false;
            }
        
        
            System.out.println("After updated balance== "+Long.parseLong(jedis.get(balance)));
            System.out.println("After updated debt== "+Long.parseLong(jedis.get(debt)));
            return true;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM