Skip to content

Instantly share code, notes, and snippets.

@rajanim
Created May 2, 2022 04:01
Show Gist options
  • Select an option

  • Save rajanim/659f3670df2e3fe09cde7e5d4115512b to your computer and use it in GitHub Desktop.

Select an option

Save rajanim/659f3670df2e3fe09cde7e5d4115512b to your computer and use it in GitHub Desktop.
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

rajanim commented May 2, 2022

Copy link
Copy Markdown
Author

image

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