1. 程式人生 > >Redis的事務處理

Redis的事務處理

Redis的事務操作

  1. multi 開啟事務
  2. exec 提交事務
  3. discard取消事務
127.0.0.1:6379> multi 
OK
127.0.0.1:6379> set djk fdjs
QUEUED
127.0.0.1:6379> set djklg djgl
QUEUED
127.0.0.1:6379> discard
OK
127.0.0.1:6379> exec
(error) ERR EXEC without MULTI

4 watch監聽key值

watch: 在事務開啟之前監聽一個或多個keys值,如果在事務執行時,客戶端進行修改該值,那麼事務都不執行。

127.0.0.1:6379> watch hello
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set hello ffff
QUEUED
127.0.0.1:6379> set name zll
QUEUED
127.0.0.1:6379> exec
(nil)

Jedis例項

public class JedisTransaction {
    private Jedis jedis;
    @Before
    public void beforeJedis(){
        jedis = JedisConnection.jedisConnection();
    }
    @Test
    public
void testTransaction(){ //事務一旦執行,客戶端發來的請求都不能打斷。 //開啟一個事務 Transaction transaction = jedis.multi(); transaction.set("hello", "world!"); transaction.mset("hashset_keys","nnnn"); transaction.lpush("list_key","hhhh"); transaction.lpush("list_key","xxx"
); transaction.exec(); System.out.println("=="+jedis.keys("*")); } @Test public void testWatch(){ jedis.watch("name"); Transaction transaction = jedis.multi(); transaction.set("hello", "world!"); //此時用客戶端,對name進行修改操作。 transaction.mset("name","tttt"); transaction.lpush("age","444"); System.out.println(transaction.exec()); } @Test public void testDiscard(){ Transaction transaction = jedis.multi(); transaction.set("hello", "world!"); //取消事務 System.out.println(transaction.discard()); } }