Redis transactions

1. Simple transactions in Redis :> Redis provides simple transactions and does not support transaction rollback

A set of commands that need to be executed together is placed between multi and exec, where multi represents the start of a transaction and exec represents the end of a transaction.

Java: Jedis Transaction code: (Redis Transaction management object, its in Redis. Clients. Jedis. Under the Transaction.

@Test public void test01(){ Jedis jedis = new Jedis("localhost",6379); Transaction = jedis.multi(); transaction.select(5); Transaction.set ("key1","value1"); transaction.set("key2","value2"); transaction.set("key3","value3"); // execute transaction transaction.exec(); }Copy the code

2. Stop transaction discard

@Test public void test02(){ Jedis jedis = new Jedis("localhost",6379); Transaction transaction = jedis.multi(); transaction.select(5); transaction.set("key2","value22"); // Interrupts a transaction, similar to rolling back transaction.discard(); }Copy the code

3. Watch command

In layman’s terms, the watch command marks a key. If a key is marked, the transaction will fail if the key is changed by someone else before the transaction is committed. In this case, you can usually try again in the program.

/** * The watch command marks a key. If the key is marked, the transaction will fail if the key is changed by someone else before the transaction is committed. In this case, it is usually possible to try again in the program. * * marks the balance first, and then checks whether the balance is sufficient. If the balance is insufficient, the mark will be cancelled and no deduction will be made. * If sufficient, start the transaction for update operation. * If the key balance is modified by someone else during this period, an error will be reported during the commit transaction (exec). * Programs can usually catch such errors and execute again until success. * */ public static void consumption(Integer money){ Jedis redis = new Jedis("localhost",6379); int balance = 100; // Balance 100; redis.select(5); // use db4 redis.set("balance", string.valueof (balance)); redis.watch("balance"); //redis.set("balance", String.valueOf(50)); Balance = integer.parseint (redis.get("balance")); System.out.println(balance); If (money > balance){system.out.println (" not enough "+money+" not enough "); redis.unwatch(); return; }else { Transaction transaction = redis.multi(); transaction.decrBy("balance",money); transaction.exec(); // Execute transaction balance = integer.parseint (redis.get("balance")); System.out.println(" Transaction completed... ); System.out.println(" spend "+money+" balance "+balance); return; }}Copy the code