Created
May 2, 2022 04:01
-
-
Save rajanim/659f3670df2e3fe09cde7e5d4115512b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import redis.clients.jedis.Jedis; | |
| import redis.clients.jedis.JedisPool; | |
| import redis.clients.jedis.JedisPoolConfig; | |
| import redis.clients.jedis.Transaction; | |
| import java.util.List; | |
| public class TransactionOpsExample { | |
| public static void main(String[] args) throws Exception { | |
| JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost"); | |
| Jedis jedis = null; | |
| try { | |
| jedis = pool.getResource(); | |
| jedis.hset("account:1", "deposit", "100"); | |
| String acc_details = jedis.hget("account:1", "deposit").toString(); | |
| System.out.println("Before watch, acc_deposit=" + acc_details); | |
| System.out.println("Watching account:1 key"); | |
| jedis.watch("account:1"); | |
| Transaction t = jedis.multi(); | |
| System.out.println("Initiated transaction block"); | |
| t.hset("account:1", "deposit", "150"); | |
| System.out.println("increasing deposit value to 150"); | |
| Thread.sleep(5000); | |
| //create new thread and increase deposit value outside of transaction queued thread | |
| new Thread(() -> { | |
| System.out.println("New thread outside of transaction block updating deposit value to 120"); | |
| Jedis jedis1 = new JedisPool(new JedisPoolConfig(), "localhost").getResource(); | |
| jedis1.hset("account:1", "deposit", "120"); | |
| }).start(); | |
| //execute transaction thread | |
| List<Object> objectList = t.exec(); | |
| //returns null | |
| if(objectList!= null) { | |
| System.out.println(jedis.hgetAll("account:1").toString()); | |
| for (Object obj : objectList) { | |
| System.out.println(obj.toString()); | |
| } | |
| }else{ | |
| System.out.println("Transaction returned null"); | |
| System.out.println("final account deposit"); | |
| System.out.println(jedis.hgetAll("account:1").toString()); | |
| } | |
| } finally { | |
| if (jedis != null) { | |
| jedis.close(); | |
| } | |
| } | |
| /// ... when closing your application: | |
| pool.destroy(); | |
| } | |
| } |
rajanim
commented
May 2, 2022
Author

Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment