Java Code Examples for redis.clients.jedis.Transaction#exec()
The following examples show how to use
redis.clients.jedis.Transaction#exec() .
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 |
@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 2
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 3
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 4
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 5
Source File: ModelDataProcessorImpl.java From searchbox-core with Apache License 2.0 | 6 votes |
@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 6
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 7
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 8
Source File: TransactionCommandsTest.java From cachecloud with Apache License 2.0 | 6 votes |
@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 9
Source File: TaskLock.java From javabase with Apache License 2.0 | 6 votes |
/** * 方案一的坏处: * 假如在极端情况下,可能出现集群各个服务器同时执行到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 10
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 11
Source File: RedisUsers.java From datashare with GNU Affero General Public License v3.0 | 5 votes |
void createUser(HashMapUser user) { try (Jedis jedis = redis.getResource()) { Transaction transaction = jedis.multi(); transaction.set(user.login(), user.toJson()); transaction.expire(user.login(), this.ttl); transaction.exec(); } }
Example 12
Source File: TransactionCommandsTest.java From cachecloud with Apache License 2.0 | 5 votes |
@Test public void unwatch() throws UnknownHostException, IOException { jedis.watch("mykey"); String val = jedis.get("mykey"); val = "foo"; String status = jedis.unwatch(); assertEquals("OK", status); Transaction t = jedis.multi(); nj.connect(); nj.auth("foobared"); nj.set("mykey", "bar"); nj.disconnect(); t.set("mykey", val); List<Object> resp = t.exec(); assertEquals(1, resp.size()); assertEquals("OK", resp.get(0)); // Binary jedis.watch(bmykey); byte[] bval = jedis.get(bmykey); bval = bfoo; status = jedis.unwatch(); assertEquals(Keyword.OK.name(), status); t = jedis.multi(); nj.connect(); nj.auth("foobared"); nj.set(bmykey, bbar); nj.disconnect(); t.set(bmykey, bval); resp = t.exec(); assertEquals(1, resp.size()); assertEquals("OK", resp.get(0)); }
Example 13
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 14
Source File: JedisNodeClient.java From session-managers with Apache License 2.0 | 5 votes |
@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 15
Source File: RedisUtil.java From Summer with Apache License 2.0 | 5 votes |
/**删除index的元素*/ public static void ldel(String key, int index) { try { Transaction multi = RedisMgr.get().getConnection().multi(); multi.lset(key, index, "__deleted__"); multi.lrem(key, 1, "__deleted__"); multi.exec(); } finally { RedisMgr.get().discardConnectionFromRedis(); } }
Example 16
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 17
Source File: RedisSessionIdStore.java From datashare with GNU Affero General Public License v3.0 | 5 votes |
@Override public void put(final String sessionId, final String login) { try (Jedis jedis = redis.getResource()) { Transaction transaction = jedis.multi(); transaction.set(sessionId, login); transaction.expire(sessionId, this.ttl); transaction.exec(); } }
Example 18
Source File: RedisRaterLimiter.java From sk-admin with Apache License 2.0 | 4 votes |
public String acquireTokenFromBucket(String point, int limit, long timeout) { try (Jedis jedis = jedisPool.getResource()) { //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("限流出错,请检查 Redis 运行状态\n" + e.toString()); } return null; }
Example 19
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 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; }