package cn.com; import java.util.List; import redis.clients.jedis.Jedis; import redis.clients.jedis.Transaction; public class Redis_Transactions { public static Jedis redis = new Jedis( "localhost" , 6379 ); // 连接redis /** * 基本事务用法 * 默认给user1,user2都初始化为1000 * 开启事务 * 给user:1:money 加一 * 给user:2:money 减一 * 执行事务 * */ public static void base_trans() throws InterruptedException{ redis.flushDB(); //清除数据 redis.set( "money" , "1000" ); redis.set( "money1" , "1000" ); long start = System.currentTimeMillis(); Transaction tx = redis.multi(); tx.incr( "money" ); //给用户user:1 加一块钱 tx.decr( "money1" ); //给用户user:1 减一块钱 List<Object> results = tx.exec(); long end = System.currentTimeMillis(); System.out.println( "Transaction SET: " + ((end - start)/ 1000.0 ) + " seconds" ); System.out.println(redis.get( "money" )); System.out.println(redis.get( "money1" )); redis.disconnect(); } /** * 用户事务 * 默认给user1,user2都初始化为1000 * 开启事务 * 给user:1:money 加一 * 给user:2:money 减一 * 我们user:2:money 的值是a 是无法执行减1 的操作 那是否还是照样执行 * 因为redis事务是比较简单的,像下面这种问题需要开发者自己控制,redis 事务是不做控制的 * */ public static void user_trans() throws InterruptedException{ redis.flushDB(); //清除数据 redis.set( "user:1:money" , "1000" ); redis.set( "user:2:money" , "a" ); long start = System.currentTimeMillis(); Transaction tx = redis.multi(); tx.incr( "user:1:money" ); //给用户user:1 加一块钱 tx.decr( "user:2:money" ); //给用户user:1 减一块钱 List<Object> results = tx.exec(); long end = System.currentTimeMillis(); System.out.println( "Transaction SET: " + ((end - start)/ 1000.0 ) + " seconds" ); System.out.println(redis.get( "user:1:money" )); System.out.println(redis.get( "user:2:money" )); redis.disconnect(); } /** * 执行事务的过程其他客户端改变了其中的key值,解决数据一致性问题 * 通过watch 对key的监控来实现其他客户端修改数据后,事务取消 * 用法 首先用watch 开始对key的监控 在开启事务,顺序一定要先监控在执行事务 * */ public static void changedata_trans() throws InterruptedException{ redis.flushDB(); //清除数据 redis.set( "user:1:money" , "1000" ); redis.set( "user:2:money" , "1000" ); long start = System.currentTimeMillis(); redis.watch( "user:1:money" ); Transaction tx = redis.multi(); tx.incr( "user:1:money" ); //给用户user:1 加一块钱 tx.decr( "user:2:money" ); //给用户user:1 减一块钱 changedata(); //改变数据的方法 List<Object> results = tx.exec(); long end = System.currentTimeMillis(); System.out.println( "Transaction SET: " + ((end - start)/ 1000.0 ) + " seconds" ); System.out.println(redis.get( "user:1:money" )); System.out.println(redis.get( "user:2:money" )); redis.disconnect(); } /** * 模拟新开客户端对事务中监控的key对应的元素进行修改 * * **/ public static void changedata(){ Jedis redis2 = new Jedis( "localhost" , 6379 ); // 连接redis redis2.set( "user:1:money" , "8888" ); } public static void main(String [] args) throws InterruptedException{ changedata_trans(); } } |