Jedis事务操作用例

public class TransactionDemo{
    
    
  
  public static void main(String[] args){
    
    
    Jedis jedis = new Jedis();
    String userId = “testId”;
    String key = keyFor(userId);
    jedis.setnx(key,String.valueOf(5));
    System.out.println(doubleAccount(jedis,userId));
  }

  public static int doubleAccount(Jedis jedis,String userId){
    
    
    String key = keyFor(userId);
    while(true){
    
    
      jedis.watch(key);
      int value = Integer.parseInt(jedis.get(key));
      value*=2;
      Transaction tx = jedis.multi();
      tx.set(key,String.valueOf(value));
      List<Object> res = tx.exec();
      if(res != null){
    
    
        break;
      }
    }
    return Integer.parseInt(jedis.get(key));
  }
  
  public static String keyFor(String userId){
    
    
    return String.format("account_%s",userId);
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/121129557