Java中的Redis事务

一次简单的事务执行

  • package cn.e3mall.common.RedisText;
    
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.Transaction;
    
    /**
     * @author Mr.Li
     * @version 1.0
     * @Description:
     * @Modified By:
     * @date 2019/1/29 13:07
     */
    public class TextTX {
    
        public static void main(String[] args) {
    
            Jedis jedis=new Jedis("127.0.0.1",6379);
    
            Transaction transaction = jedis.multi();
            transaction.set("k5","v5");
            transaction.set("k6","v6");
            transaction.set("k7","v7");
    
            /**
             * 执行下面命令运行事务块
             * transaction.exec();
             */
    
            /**
             * 取消事务,放弃执行事务块内的所有命令
             * transaction.discard();
             */
        }
    }
    

     

购买物品的事务执行 

  • package cn.e3mall.common.RedisText;
    
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.Transaction;
    
    /**
     * @author Mr.Li
     * @version 1.0
     * @Description:
     * @Modified By:
     * @date 2019/1/29 13:07
     */
    public class TextTX {
    
        public static void main(String[] args) {
    
            TextTX test=new TextTX();
            boolean retValue=test.transMethod();
            System.out.println("main retValue----------:"+retValue);
    
        }
    
        private boolean transMethod() {
            Jedis jedis = new Jedis("127.0.0.1", 6379);
    
            int balance;                //可用余额
            int debt;                   //欠费
            int amtToSubtract = 10;     //实刷额度
    
            jedis.watch("balance");
    
            balance = Integer.parseInt(jedis.get("balance"));
            //如果可用余额小于实刷额度
            if (balance < amtToSubtract) {
                jedis.unwatch();
                System.out.println("modify");
                return false;
            } else {
                System.out.println("******开启事务******");
                Transaction transaction=jedis.multi();
                transaction.decrBy("balacne",amtToSubtract);
                transaction.incrBy("debt",amtToSubtract);
                transaction.exec();
                balance = Integer.parseInt(jedis.get("balance"));
                debt = Integer.parseInt(jedis.get("debt"));
    
                System.out.println("可用余额" + balance);
                System.out.println("欠费" + debt);
                return true;
            }
        }
    }
    

     

你可能感兴趣的:(Redis)