Java Code Examples for redis.clients.jedis.Transaction#sadd()

The following examples show how to use redis.clients.jedis.Transaction#sadd() . 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: 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 2
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 3
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 4
Source File: TransactionCommandsTest.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
@Test
public void multi() {
  Transaction trans = jedis.multi();

  trans.sadd("foo", "a");
  trans.sadd("foo", "b");
  trans.scard("foo");

  List<Object> response = trans.exec();

  List<Object> expected = new ArrayList<Object>();
  expected.add(1L);
  expected.add(1L);
  expected.add(2L);
  assertEquals(expected, response);

  // Binary
  trans = jedis.multi();

  trans.sadd(bfoo, ba);
  trans.sadd(bfoo, bb);
  trans.scard(bfoo);

  response = trans.exec();

  expected = new ArrayList<Object>();
  expected.add(1L);
  expected.add(1L);
  expected.add(2L);
  assertEquals(expected, response);

}
 
Example 5
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();
    }
}
 
Example 6
Source File: SeckillServiceImpl.java    From jseckill with Apache License 2.0 4 votes vote down vote up
/**
 * @param seckillId
 * @param userPhone
 * @param md5
 * @return
 * @throws SeckillException
 * @TODO 先在redis里处理,然后发送到mq,最后减库存到数据库
 */
private SeckillExecution handleSeckillAsync(long seckillId, long userPhone, String md5)
        throws SeckillException {
    if (md5 == null || !md5.equals(getMD5(seckillId))) {
        logger.info("seckill_DATA_REWRITE!!!. seckillId={},userPhone={}", seckillId, userPhone);
        throw new SeckillException(SeckillStateEnum.DATA_REWRITE);
    }

    Jedis jedis = jedisPool.getResource();
    String inventoryKey = RedisKeyPrefix.SECKILL_INVENTORY + seckillId;
    if (jedis.sismember(RedisKey.SECKILLED_USER, String.valueOf(userPhone))) {
        //重复秒杀
        logger.info("seckill REPEATED. seckillId={},userPhone={}", seckillId, userPhone);
        throw new SeckillException(SeckillStateEnum.REPEAT_KILL);
    } else {
        String inventoryStr = jedis.get(inventoryKey);
        int inventory = Integer.valueOf(inventoryStr);
        if (inventory <= 0) {
            throw new SeckillException(SeckillStateEnum.SOLD_OUT);
        }
        jedis.watch(inventoryKey);
        Transaction tx = jedis.multi();
        tx.decr(inventoryKey);
        tx.sadd(RedisKey.SECKILLED_USER, String.valueOf(userPhone));
        List<Object> resultList = tx.exec();
        jedis.unwatch();
        if (resultList != null && resultList.size() == 2) {
            // 秒杀成功,后面异步更新到数据库中
            // 发送消息到消息队列
            SeckillMsgBody msgBody = new SeckillMsgBody();
            msgBody.setSeckillId(seckillId);
            msgBody.setUserPhone(userPhone);
            mqProducer.send(JSON.toJSONString(msgBody));

            // 立即返回给客户端,说明秒杀成功了
            SuccessKilled successKilled = new SuccessKilled();
            successKilled.setUserPhone(userPhone);
            successKilled.setSeckillId(seckillId);
            successKilled.setState(SeckillStateEnum.SUCCESS.getState());
            return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
        } else {
            throw new SeckillException(SeckillStateEnum.RUSH_FAILED);
        }
    }
}