日常操作
public static void main(String[] args) { Jedis jedis = new Jedis("192.168.222.129", 6379); //1、开启事务 Transaction transaction = jedis.multi(); //2、执行 transaction.set("k4", "v4"); transaction.set("k5", "v5"); //3、提交事务 transaction.exec(); //4、放弃事务 //transaction.discard(); }
加锁事务
public static void main(String[] args) { TestTx testTx = new TestTx(); boolean retValue = testTx.transMethod(); System.out.println("main=====return value " + retValue); } private boolean transMethod() { // TODO Auto-generated method stub Jedis jedis = new Jedis("192.168.222.129", 6379); int balance; //可用余额 int debt;//欠额 int pay = 10;//实际话费金额 jedis.watch("balance"); balance = Integer.parseInt(jedis.get("balance")); if (balance < pay) { jedis.unwatch(); System.out.println("您的余额不足"); return false; } else { System.out.println("============开会消费========"); //1、开启事务 Transaction transaction = jedis.multi(); //2、执行 transaction.decrBy("balance", pay); transaction.incrBy("debt", pay); //3、提交事务 transaction.exec(); balance = Integer.parseInt(jedis.get("balance")); debt = Integer.parseInt(jedis.get("debt")); System.out.println("余额: " + balance); System.err.println("花费: " + debt); return true; } }
结果
============开会消费======== 余额: 90 main=====return value true 花费: 10