docs
uredis
Product Application
Application Scenario
Transaction processing

Transaction Processing

Users can use the MULTI, EXEC, DISCARD, WATCH, UNWATCH commands to perform atomic transaction operations.

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import java.util.List;
public class JTransaction {
    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 10011;
        Jedis jedis1 = new Jedis(host, port);
        Jedis jedis2 = new Jedis(host, port);
        String key = "transaction-key";
        jedis1.set(key, "20");
        //jedis1 watch key
        jedis1.watch(key);//if other clients change the key before executing the transaction, the transaction will fail.
        Transaction tx = jedis1.multi();//start transaction
        tx.get(key);
        tx.get(key);
        tx.get(key);
        //jedis2.incr(key);//if jedis2 alters the key, the transaction of jedis1 will fail 
        List<Object> result = tx.exec();//execute transaction
        if(result == null || result.isEmpty()){
            System.out.println("Transaction error...");
            return;
        }
        for(Object rt : result){
            System.out.println(rt.toString());
        }
    }
}

Output:

20
20
20
  • Company
  • ContactUs
  • Blog
Copyright © 2024 SurferCloud All Rights Reserved