redis.clients.jedis.Transaction Java Examples

The following examples show how to use redis.clients.jedis.Transaction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransactionCommandsTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseable() throws IOException {
  // we need to test with fresh instance of Jedis
  Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
  jedis2.auth("foobared");

  Transaction transaction = jedis2.multi();
  transaction.set("a", "1");
  transaction.set("b", "2");

  transaction.close();

  try {
    transaction.exec();
    fail("close should discard transaction");
  } catch (JedisDataException e) {
    assertTrue(e.getMessage().contains("EXEC without MULTI"));
    // pass
  }
}
 
Example #2
Source File: JedisIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenMultipleOperationsThatNeedToBeExecutedAtomically_thenWrapThemInATransaction() {
    String friendsPrefix = "friends#";

    String userOneId = "4352523";
    String userTwoId = "5552321";

    Transaction t = jedis.multi();
    t.sadd(friendsPrefix + userOneId, userTwoId);
    t.sadd(friendsPrefix + userTwoId, userOneId);
    t.exec();

    boolean exists = jedis.sismember(friendsPrefix + userOneId, userTwoId);
    Assert.assertTrue(exists);

    exists = jedis.sismember(friendsPrefix + userTwoId, userOneId);
    Assert.assertTrue(exists);
}
 
Example #3
Source File: JedisDriver.java    From redis-scheduler with MIT License 6 votes vote down vote up
@Override
public boolean exec() {
    try {
        return Optional.ofNullable(txn)
                       .map(Transaction::exec)
                       .map(col -> !col.isEmpty())
                       .orElse(false);
    } finally {
        try {
            txn.close();
        } catch (IOException e) {
            throw new RedisConnectException(e);
        }
        txn = null;
    }
}
 
Example #4
Source File: JedisTransactionDemo.java    From Redis-4.x-Cookbook with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    //Connecting to localhost Redis server
    Jedis jedis = new Jedis("localhost");

    //Initialize
    String user = "user:1000";
    String restaurantOrderCount = "restaurant_orders:200";
    String restaurantUsers = "restaurant_users:200";
    jedis.set(restaurantOrderCount, "400");
    jedis.sadd(restaurantUsers, "user:302", "user:401");

    //Create a Redis transaction
    Transaction transaction = jedis.multi();
    Response<Long> countResponse = transaction.incr(restaurantOrderCount);
    transaction.sadd(restaurantUsers, user);
    Response<Set<String>> userSet = transaction.smembers(restaurantUsers);
    //Execute transaction
    transaction.exec();

    //Handle responses
    System.out.printf("Number of orders: %d\n", countResponse.get());
    System.out.printf("Users: %s\n", userSet.get());
    System.exit(0);
}
 
Example #5
Source File: JedisApiTest.java    From easyooo-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 一个client发起的事务中的命令可以连续的执行,而中间不会插入其他client的命令。
 */
@Test
@Ignore
public void testTransactions(){
	Jedis jedis = new Jedis("localhost");
	long start = System.currentTimeMillis();
	Transaction tx = jedis.multi();
	
	for(int i = 0; i< COUNTER; i++){
		tx.set("t" + i, "t" + i);
		// 提示使用JedisTransaction代替
		if(i == 100){
			System.out.println(jedis.get("t1"));
			
			// 无法读取到,是正确的
			//System.out.println(new Jedis("localhost").get("t1"));
		}
	}
	List<Object> results = tx.exec();
	long end = System.currentTimeMillis();
	logger.info("Tx Set: " + ((end - start)/1000.0) + " seconds");
	jedis.close();
	System.out.println("results: " + results);
}
 
Example #6
Source File: DefaultRedisTransactionCallback.java    From easyooo-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void doCallback(Transaction tx) {
	for (Command cmd : redisCommands) {
		switch (cmd.getOp()) {
			case SET:
				tx.set(cmd.getCacheKey(), cmd.getCacheValue());
				break;
			case MOD:
				tx.set(cmd.getCacheKey(), cmd.getCacheValue());
				break;
			case DEL:
				tx.del(cmd.getCacheKey());
				break;
			case ADD_MEMBERS:
				tx.sadd(cmd.getCacheGroupKey(), cmd.getGroupValues());
				break;
			case DEL_MEMBERS:
				tx.srem(cmd.getCacheGroupKey(), cmd.getGroupValues());
				break;
			case SETS:
				tx.mset(cmd.getKeyvalues());
			default:
				break;
		}
	}
}
 
Example #7
Source File: PasswordDB.java    From VileBot with MIT License 6 votes vote down vote up
/**
 * Remove a user and their password information, if they exist.
 * 
 * @param username unique user name
 */
public static void remUserPassword( String username )
{
    Jedis jedis = pool.getResource();
    try
    {
        Transaction trans = jedis.multi();
        trans.hdel( keyOfPassHash, username );
        trans.hdel( keyOfPassSaltsHash, username );
        trans.exec();
    }
    finally
    {
        pool.returnResource( jedis );
    }
}
 
Example #8
Source File: StockWithRedis.java    From seconds-kill with MIT License 6 votes vote down vote up
/**
 * 重置缓存
 */
public static void initRedisBefore() {
    Jedis jedis = null;
    try {
        jedis = RedisPool.getJedis();
        // 开始事务
        Transaction transaction = jedis.multi();
        // 事务操作
        RedisPoolUtil.set(RedisKeysConstant.STOCK_COUNT + 1, "50");
        RedisPoolUtil.set(RedisKeysConstant.STOCK_SALE + 1, "0");
        RedisPoolUtil.set(RedisKeysConstant.STOCK_VERSION + 1, "0");
        // 结束事务
        List<Object> list = transaction.exec();
    } catch (Exception e) {
        log.error("initRedis 获取 Jedis 实例失败:", e);
    } finally {
        RedisPool.jedisPoolClose(jedis);
    }
}
 
Example #9
Source File: StockWithRedis.java    From seconds-kill with MIT License 6 votes vote down vote up
/**
 * Redis 事务保证库存更新
 * 捕获异常后应该删除缓存
 */
public static void updateStockWithRedis(Stock stock) {
    Jedis jedis = null;
    try {
        jedis = RedisPool.getJedis();
        // 开始事务
        Transaction transaction = jedis.multi();
        // 事务操作
        RedisPoolUtil.decr(RedisKeysConstant.STOCK_COUNT + stock.getId());
        RedisPoolUtil.incr(RedisKeysConstant.STOCK_SALE + stock.getId());
        RedisPoolUtil.incr(RedisKeysConstant.STOCK_VERSION + stock.getId());
        // 结束事务
        List<Object> list = transaction.exec();
    } catch (Exception e) {
        log.error("updateStock 获取 Jedis 实例失败:", e);
    } finally {
        RedisPool.jedisPoolClose(jedis);
    }
}
 
Example #10
Source File: TransactionTest.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 乐观锁:watch
 *
 */
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)); // 重新获取余额
}
 
Example #11
Source File: RedisDaoTemplate.java    From javabase with Apache License 2.0 6 votes vote down vote up
public void execute(TransactionCallBack rc) {
	Jedis jedis = null;
	Transaction transaction;
	List<Object> object = null;
	try {
		jedis = RedisPool.getJedis();
		transaction = jedis.multi();
		rc.execute(transaction);
		object = transaction.exec();
	} catch (Exception e) {
		log.error("执行redis操作异常" + e.getLocalizedMessage());
	}
	finally {
		RedisPool.returnJedis(jedis);
	}
}
 
Example #12
Source File: TaskLock.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * 方案一的坏处:
 * 假如在极端情况下,可能出现集群各个服务器同时执行到taskLockVersionOne,或者 doTask执行时间过长,
 * 在redis事物还没提交的时候,会出现同时有多台服务器执行doTask。
 * @param id
 */
private static void taskLockVersionOne(String id) {
	String key = "default_task_id";
	String value = jedis.get(key);
	// 用redis 事物是防止 在set成功之后 在执行doTask或者其他情况导致程序终止没有执行到transaction.expire()
	// 导致单台机器一直占着锁会有单点事故
	Transaction transaction = null;
	try {
		transaction = jedis.multi();
		if (value == null) {
			transaction.set(key, id);
			doTask(id);
			// 设置过期是防止单点错误
			transaction.expire(key, 30);
		} else {
			if (value.equals(id)) {
				doTask(id);
			}
		}
	} catch (Exception e) {
		log.error("e" + e);
	} finally {
		transaction.exec();
	}
}
 
Example #13
Source File: ServiceCapacityInterceptor.java    From moon-api-gateway with MIT License 6 votes vote down vote up
@Override
public Map<String, Response<Long>> setJedisMultiCommand(Transaction jedisMulti) {
    String dailyRedisKey = String.join(":", Constant.REDIS_SERVICE_CAPACITY_DAILY, String.valueOf(requestInfo.getServiceId()));
    String minutelyRedisKey = String.join(":", Constant.REDIS_SERVICE_CAPACITY_MINUTELY, String.valueOf(requestInfo.getServiceId()));

    Response<Long> serviceDailyRatelimit = jedisMulti.decr(dailyRedisKey);
    Response<Long> serviceMinutelyRatelimit = jedisMulti.decr(minutelyRedisKey);
    Response<Long> serviceDailyTTL = jedisMulti.ttl(dailyRedisKey);
    Response<Long> serviceMinutelyTTL = jedisMulti.ttl(minutelyRedisKey);

    Map<String, Response<Long>> serviceRatelimit = Maps.newHashMap();
    serviceRatelimit.put(Constant.REDIS_SERVICE_CAPACITY_DAILY, serviceDailyRatelimit);
    serviceRatelimit.put(Constant.REDIS_SERVICE_CAPACITY_DAILY_TTL, serviceDailyTTL);
    serviceRatelimit.put(Constant.REDIS_SERVICE_CAPACITY_MINUTELY, serviceMinutelyRatelimit);
    serviceRatelimit.put(Constant.REDIS_SERVICE_CAPACITY_MINUTELY_TTL, serviceMinutelyTTL);

    return serviceRatelimit;
}
 
Example #14
Source File: TaskLock.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * 方案二:
 * 会重复两次回去jedis.get(key);
 * 同时如果expire时间小于doTask时间,也会出现同时有两个任务执行doTask情况。
 * @param id
 */
private static void taskLockVersionTwo(String id) {
	String key = "default_task_id";
	String value = jedis.get(key);
	// 用redis 事物是防止 在set成功之后 在执行doTask或者其他情况导致程序终止没有执行到transaction.expire()
	// 导致单台机器一直占着锁会有单点事故
	Transaction transaction = null;
	try {
		transaction = jedis.multi();
		if (value == null) {
			transaction.set(key, id);
			transaction.expire(key, 30);
		}
	} catch (Exception e) {
		log.error("e" + e);
	} finally {
		transaction.exec();
	}
	value = jedis.get(key);
	if (value.equals(id)) {
		doTask(id);
	}
}
 
Example #15
Source File: TransactionCommandsTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void testResetStateWithFullyExecutedTransaction() {
  Jedis jedis2 = new Jedis(jedis.getClient().getHost(), jedis.getClient().getPort());
  jedis2.auth("foobared");

  Transaction t = jedis2.multi();
  t.set("mykey", "foo");
  t.get("mykey");

  List<Object> resp = t.exec();
  assertNotNull(resp);
  assertEquals(2, resp.size());

  jedis2.resetState();
  jedis2.close();
}
 
Example #16
Source File: TransactionCommandsTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void testResetStateWhenInWatch() {
  jedis.watch("mykey", "somekey");

  // state reset : unwatch
  jedis.resetState();

  Transaction t = jedis.multi();

  nj.connect();
  nj.auth("foobared");
  nj.set("mykey", "bar");
  nj.disconnect();

  t.set("mykey", "foo");
  List<Object> resp = t.exec();
  assertNotNull(resp);
  assertEquals(1, resp.size());
  assertEquals("foo", jedis.get("mykey"));
}
 
Example #17
Source File: TransactionCommandsTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void select() {
  jedis.select(1);
  jedis.set("foo", "bar");
  jedis.watch("foo");
  Transaction t = jedis.multi();
  t.select(0);
  t.set("bar", "foo");

  Jedis jedis2 = createJedis();
  jedis2.select(1);
  jedis2.set("foo", "bar2");

  List<Object> results = t.exec();

  assertNull(results);
}
 
Example #18
Source File: TransactionCommandsTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void execGetResponse() {
  Transaction t = jedis.multi();

  t.set("foo", "bar");
  t.smembers("foo");
  t.get("foo");

  List<Response<?>> lr = t.execGetResponse();
  try {
    lr.get(1).get();
    fail("We expect exception here!");
  } catch (JedisDataException e) {
    // that is fine we should be here
  }
  assertEquals("bar", lr.get(2).get());
}
 
Example #19
Source File: TransactionCommandsTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void transactionResponseWithError() {
  Transaction t = jedis.multi();
  t.set("foo", "bar");
  Response<Set<String>> error = t.smembers("foo");
  Response<String> r = t.get("foo");
  List<Object> l = t.exec();
  assertEquals(JedisDataException.class, l.get(1).getClass());
  try {
    error.get();
    fail("We expect exception here!");
  } catch (JedisDataException e) {
    // that is fine we should be here
  }
  assertEquals(r.get(), "bar");
}
 
Example #20
Source File: ReusableSequenceService.java    From captain with Apache License 2.0 6 votes vote down vote up
public int nextId(String name) {
	String key = keyFor(name);
	Holder<Integer> holder = new Holder<>();
	redis.execute(jedis -> {
		jedis.sadd(ALL_SEQS, name);
		long pos = 0;
		do {
			jedis.watch(key);
			pos = jedis.bitpos(key, false);
			if (pos < 0) {
				pos = 0;
			}
			Transaction tx = jedis.multi();
			tx.setbit(key, pos, true);
			if (tx.exec() != null) {
				break;
			}
		} while (true);
		holder.set((int) pos);
	});
	return holder.value();
}
 
Example #21
Source File: RedisExample.java    From java-platform with Apache License 2.0 6 votes vote down vote up
public void testTrans() {// 0.304秒
	Jedis jedis = new Jedis("120.25.241.144", 6379);
	jedis.auth("b840fc02d52404542994");

	long start = System.currentTimeMillis();
	Transaction tx = jedis.multi();
	for (int i = 0; i < 1000; i++) {
		tx.set("n" + i, "n" + i);
		System.out.println(i);
	}
	tx.exec();
	long end = System.currentTimeMillis();
	System.out.println("共花费:" + (end - start) / 1000.0 + "秒");

	jedis.disconnect();
	try {
		Closeables.close(jedis, true);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example #22
Source File: ModelDataProcessorImpl.java    From searchbox-core with Apache License 2.0 6 votes vote down vote up
@Override
public void storeModel(String modelName, String id, String object) throws Exception{

       try(Jedis jedis = pool.getResource()){
       	
   		Map<String, String> map = new HashMap<>();
   		map.put(id, object);
   		
   		String hm_key = createKey(table_perfix, modelName);
   		
   		while(true){
    		jedis.watch(hm_key);
    		Transaction transaction = jedis.multi();
    		transaction.hmset(hm_key, map);
    		if(transaction.exec() != null)
    			break;
   		}

       }
	
}
 
Example #23
Source File: ApplicationRatelimitInterceptor.java    From moon-api-gateway with MIT License 6 votes vote down vote up
@Override
public Map<String, Response<Long>> setJedisMultiCommand(Transaction jedisMulti) {

    String dailyRedisKey = String.join(":", Constant.REDIS_APP_RATELIMIT_DAILY, String.valueOf(requestInfo.getServiceId()), String.valueOf(requestInfo.getAppId()));
    String minutelyRedisKey = String.join(":", Constant.REDIS_APP_RATELIMIT_MINUTELY, String.valueOf(requestInfo.getServiceId()), String.valueOf(requestInfo.getAppId()));

    Response<Long> applicationDailyRateLimit = jedisMulti.decr(dailyRedisKey);
    Response<Long> applicationMinutelyRateLimit = jedisMulti.decr(minutelyRedisKey);
    Response<Long> applicationDailyRateLimitTTL = jedisMulti.ttl(dailyRedisKey);
    Response<Long> applicationMinutelyRateLimitTTL = jedisMulti.ttl(minutelyRedisKey);

    Map<String, Response<Long>> appRatelimit = Maps.newHashMap();
    appRatelimit.put(Constant.REDIS_APP_RATELIMIT_DAILY, applicationDailyRateLimit);
    appRatelimit.put(Constant.REDIS_APP_RATELIMIT_MINUTELY, applicationMinutelyRateLimit);
    appRatelimit.put(Constant.REDIS_APP_RATELIMIT_DAILY_TTL, applicationDailyRateLimitTTL);
    appRatelimit.put(Constant.REDIS_APP_RATELIMIT_MINUTELY_TTL, applicationMinutelyRateLimitTTL);

    return appRatelimit;

}
 
Example #24
Source File: RedisParamServerClient.java    From digdag with Apache License 2.0 6 votes vote down vote up
@Override
public void commit()
{
    if (connection != null) {
        if (!msetTarget.isEmpty()) {
            Transaction multi = connection.multi();
            for (Map.Entry<String, String> entry : msetTarget.entrySet()) {
                multi.setex(entry.getKey(), DEFAULT_TTL_IN_SEC, entry.getValue());
            }
            multi.exec();
        }
        msetTarget.clear();

        // `connection` object is created for every time when ParamServerClientConnection
        // is injected, and is not a singleton object.
        // So we must close connection manually.
        connection.close();
        this.connection = null;
    }
}
 
Example #25
Source File: JedisPoolTest.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
@Test
public void returnResourceShouldResetState() {
  GenericObjectPoolConfig config = new GenericObjectPoolConfig();
  config.setMaxTotal(1);
  config.setBlockWhenExhausted(false);
  JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared");

  Jedis jedis = pool.getResource();
  try {
    jedis.set("hello", "jedis");
    Transaction t = jedis.multi();
    t.set("hello", "world");
  } finally {
    jedis.close();
  }

  Jedis jedis2 = pool.getResource();
  try {
    assertTrue(jedis == jedis2);
    assertEquals("jedis", jedis2.get("hello"));
  } finally {
    jedis2.close();
  }

  pool.destroy();
  assertTrue(pool.isClosed());
}
 
Example #26
Source File: PasswordDB.java    From VileBot with MIT License 5 votes vote down vote up
/**
 * Add or modify a user's password
 * 
 * @param username unique user name
 * @param password the user's password (will be hashed)
 * @return true iff a new element was inserted
 */
public static boolean setUserPassword( String username, String password )
{
    Jedis jedis = pool.getResource();
    try
    {
        boolean newUser;

        Transaction trans;
        do
        {
            // Can't use intermediate results of a Redis transaction in that transaction, so watch the keys and do
            // the query before opening the transaction. The transaction will fail on exec() call if the keys
            // changed.
            jedis.watch( keyOfPassHash, keyOfPassSaltsHash );
            boolean exists = jedis.hexists( keyOfPassHash, username );

            trans = jedis.multi();
            // Create a salt as well as the new password entry if the user is new
            if ( !exists )
            {
                newUser = true;

                String salt = generateSalt();
                trans.hset( keyOfPassSaltsHash, username, salt );

                String hash = hash( password, salt );
                trans.hset( keyOfPassHash, username, hash );
            }
            else
                newUser = false;
        }
        while ( trans.exec() == null );

        return newUser;
    }
    finally
    {
        pool.returnResource( jedis );
    }
}
 
Example #27
Source File: JedisNodeClient.java    From session-managers with Apache License 2.0 5 votes vote down vote up
@Override
public void clean(String sessionsKey) {
    try(Jedis jedis = this.jedisPool.getResource()) {
        Set<String> sessions = jedis.smembers(sessionsKey);
        String[] sessionsArray = sessions.toArray(new String[sessions.size()]);

        Transaction t = jedis.multi();
        t.srem(sessionsKey, sessionsArray);
        t.del(sessionsArray);
        t.exec();
    }
}
 
Example #28
Source File: JedisSentinelPoolTest.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
@Test
public void returnResourceShouldResetState() {
  GenericObjectPoolConfig config = new GenericObjectPoolConfig();
  config.setMaxTotal(1);
  config.setBlockWhenExhausted(false);
  JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, config, 1000,
      "foobared", 2);

  Jedis jedis = pool.getResource();
  Jedis jedis2 = null;

  try {
    jedis.set("hello", "jedis");
    Transaction t = jedis.multi();
    t.set("hello", "world");
    jedis.close();

    jedis2 = pool.getResource();

    assertTrue(jedis == jedis2);
    assertEquals("jedis", jedis2.get("hello"));
  } catch (JedisConnectionException e) {
    if (jedis2 != null) {
      jedis2 = null;
    }
  } finally {
    jedis2.close();

    pool.destroy();
  }
}
 
Example #29
Source File: JedisNodeClient.java    From session-managers with Apache License 2.0 5 votes vote down vote up
@Override
public void del(String sessionsKey, String key) {
    try(Jedis jedis = this.jedisPool.getResource()) {
        Transaction t = jedis.multi();
        t.srem(sessionsKey, key);
        t.del(key);
        t.exec();
    }
}
 
Example #30
Source File: JedisNodeClient.java    From session-managers with Apache License 2.0 5 votes vote down vote up
@Override
public void set(String key, String sessionsKey, byte[] session, int timeout) throws UnsupportedEncodingException {
    try(Jedis jedis = this.jedisPool.getResource()) {
        Transaction t = jedis.multi();
        t.setex(key.getBytes(Protocol.CHARSET), timeout, session);
        t.sadd(sessionsKey, key);
        t.exec();
    }
}