Java Code Examples for redis.clients.jedis.Jedis#multi()
The following examples show how to use
redis.clients.jedis.Jedis#multi() .
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: TransactionTest.java From code with Apache License 2.0 | 6 votes |
/** * 乐观锁: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 2
Source File: PasswordDB.java From VileBot with MIT License | 6 votes |
/** * 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 3
Source File: JedisApiTest.java From easyooo-framework with Apache License 2.0 | 6 votes |
/** * 一个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 4
Source File: RedisExample.java From java-platform with Apache License 2.0 | 6 votes |
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 5
Source File: TransactionCommandsTest.java From cachecloud with Apache License 2.0 | 6 votes |
@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 6
Source File: TransactionCommandsTest.java From cachecloud with Apache License 2.0 | 6 votes |
@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 7
Source File: RedisDaoTemplate.java From javabase with Apache License 2.0 | 6 votes |
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 8
Source File: JedisTransactionDemo.java From Redis-4.x-Cookbook with MIT License | 6 votes |
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 9
Source File: StockWithRedis.java From seconds-kill with MIT License | 6 votes |
/** * 重置缓存 */ 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 10
Source File: StockWithRedis.java From seconds-kill with MIT License | 6 votes |
/** * 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 11
Source File: RedisDaoTemplate.java From javabase with Apache License 2.0 | 5 votes |
public void execute(TransactionCallBack rc) throws Exception { Jedis jedis = null; Transaction transaction; List<Object> object = null; try { jedis = redisPool.getJedis(); transaction = jedis.multi(); rc.execute(transaction); object = transaction.exec(); } finally { redisPool.returnJedis(jedis); } }
Example 12
Source File: RedisClient.java From Mykit with Apache License 2.0 | 5 votes |
/** * list<String>结构的数据写入redis * @param key * @param value * @return */ public boolean lpush(String key, List<String> value) { Jedis client = jedisPool.getResource(); try { Transaction tx = client.multi(); for (String one : value) { tx.lpush(key, one); } tx.exec(); return true; } finally { // 向连接池“归还”资源 jedisPool.returnResourceObject(client); } }
Example 13
Source File: RedisDistributedLock.java From Distributed-KV with Apache License 2.0 | 5 votes |
@Override public boolean unLock(String lockName, String lockSerialNum) { boolean result = false; String lock = "lock:" + lockName; Jedis conn = pool.getResource(); // 循环尝试解锁 // while循环适用于超时剥夺锁的情况 while (true) { try { // 监视锁数据,一旦被人篡改则重试 conn.watch(lock); // 当确认是自己上的锁时,利用实务进行解锁操作 if (conn.get(lock).equals(lockSerialNum)) { Transaction transaction = conn.multi(); transaction.del(lock); // 执行操作可能有隐患 transaction.exec(); result = true; System.out.println(Thread.currentThread().getName() + "redis锁解锁成功"); System.out.println("+++++++++++++++++++"); } conn.unwatch(); break; } catch (JedisException e) { // conn.watch(lock)触发,重试解锁 System.out.println(Thread.currentThread().getName() + "redis锁已被篡改,正在重试..."); System.out.println("+++++++++++++++++++"); // e.printStackTrace(); } finally { // 关闭redis连接 conn.close(); } } return result; }
Example 14
Source File: JedisPoolTest.java From cachecloud with Apache License 2.0 | 5 votes |
@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 15
Source File: JedisSentinelPoolTest.java From cachecloud with Apache License 2.0 | 5 votes |
@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 16
Source File: PasswordDB.java From VileBot with MIT License | 5 votes |
/** * 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 17
Source File: SeckillServiceImpl.java From jseckill with Apache License 2.0 | 4 votes |
/** * @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); } } }
Example 18
Source File: RedisValidator.java From moon-api-gateway with MIT License | 4 votes |
public RedisValidator(Jedis jedis) { this.jedis = jedis; this.jedisMulti = jedis.multi(); this.futureMethodQueue = new LinkedHashMap<>(); }
Example 19
Source File: DefaultRedis.java From craft-atom with MIT License | 4 votes |
private RedisTransaction multi0(Jedis j) { Transaction t = j.multi(); bind(j); return new DefaultRedisTransaction(j, t, this); }
Example 20
Source File: RedisRaterLimiter.java From BigDataPlatform with GNU General Public License v3.0 | 4 votes |
public String acquireTokenFromBucket(String point, int limit, long timeout) { Jedis jedis = jedisPool.getResource(); try{ //UUID令牌 String token = UUID.randomUUID().toString(); long now = System.currentTimeMillis(); //开启事务 Transaction transaction = jedis.multi(); //删除信号量 移除有序集中指定区间(score)内的所有成员 ZREMRANGEBYSCORE key min max transaction.zremrangeByScore((BUCKET_MONITOR + point).getBytes(), "-inf".getBytes(), String.valueOf(now - timeout).getBytes()); //为每个有序集分别指定一个乘法因子(默认设置为 1) 每个成员的score值在传递给聚合函数之前都要先乘以该因子 ZParams params = new ZParams(); params.weightsByDouble(1.0, 0.0); //计算给定的一个或多个有序集的交集 transaction.zinterstore(BUCKET + point, params, BUCKET + point, BUCKET_MONITOR + point); //计数器自增 transaction.incr(BUCKET_COUNT); List<Object> results = transaction.exec(); long counter = (Long) results.get(results.size() - 1); transaction = jedis.multi(); //Zadd 将一个或多个成员元素及其分数值(score)加入到有序集当中 transaction.zadd(BUCKET_MONITOR + point, now, token); transaction.zadd(BUCKET + point, counter, token); transaction.zrank(BUCKET + point, token); results = transaction.exec(); //获取排名,判断请求是否取得了信号量 long rank = (Long) results.get(results.size() - 1); if (rank < limit) { return token; } else { //没有获取到信号量,清理之前放入redis中垃圾数据 transaction = jedis.multi(); //Zrem移除有序集中的一个或多个成员 transaction.zrem(BUCKET_MONITOR + point, token); transaction.zrem(BUCKET + point, token); transaction.exec(); } }catch (Exception e){ log.error("限流出错"+e.toString()); }finally { if(jedis!=null){ jedis.close(); } } return null; }