public List<Object> exec() { // Discard QUEUED or ERROR client.getMany(getPipelinedResponseLength()); client.exec(); //client.getAll(1); // Discard all but the last reply inTransaction = false; List<Object> unformatted = client.getObjectMultiBulkReply(); if (unformatted == null) { return null; } List<Object> formatted = new ArrayList<Object>(); for (Object o : unformatted) { try { formatted.add(generateResponse(o).get()); } catch (JedisDataException e) { formatted.add(e); } } return formatted; }
private static void processError(final RedisInputStream is) { String message = is.readLine(); // TODO: I'm not sure if this is the best way to do this. // Maybe Read only first 5 bytes instead? if (message.startsWith(MOVED_RESPONSE)) { String[] movedInfo = parseTargetHostAndSlot(message); throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], Integer.valueOf(movedInfo[2])), Integer.valueOf(movedInfo[0])); } else if (message.startsWith(ASK_RESPONSE)) { String[] askInfo = parseTargetHostAndSlot(message); throw new JedisAskDataException(message, new HostAndPort(askInfo[1], Integer.valueOf(askInfo[2])), Integer.valueOf(askInfo[0])); } else if (message.startsWith(CLUSTERDOWN_RESPONSE)) { throw new JedisClusterException(message); } else if (message.startsWith(BUSY_RESPONSE)) { throw new JedisBusyException(message); } else if (message.startsWith(NOSCRIPT_RESPONSE)) { throw new JedisNoScriptException(message); } throw new JedisDataException(message); }
public T get() { // if response has dependency response and dependency is not built, // build it first and no more!! if (dependency != null && dependency.set && !dependency.built) { dependency.build(); } if (!set) { throw new JedisDataException("Please close pipeline or multi block before calling this method."); } if (!built) { build(); } if (exception != null) { throw exception; } return response; }
private void build() { // check build state to prevent recursion if (building) { return; } building = true; try { if (data != null) { if (data instanceof JedisDataException) { exception = (JedisDataException) data; } else { response = builder.build(data); } } data = null; } finally { building = false; built = true; } }
@Override public List<Object> build(Object data) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>) data; List<Object> values = new ArrayList<Object>(); if (list.size() != responses.size()) { throw new JedisDataException("Expected data size " + responses.size() + " but was " + list.size()); } for (int i = 0; i < list.size(); i++) { Response<?> response = responses.get(i); response.set(list.get(i)); Object builtResponse; try { builtResponse = response.get(); } catch (JedisDataException e) { builtResponse = e; } values.add(builtResponse); } return values; }
/** * Synchronize pipeline by reading all responses. This operation close the pipeline. Whenever * possible try to avoid using this version and use Pipeline.sync() as it won't go through all the * responses and generate the right response type (usually it is a waste of time). * @return A list of all the responses in the order you executed them. */ public List<Object> syncAndReturnAll() { if (getPipelinedResponseLength() > 0) { List<Object> unformatted = client.getAll(); List<Object> formatted = new ArrayList<Object>(); for (Object o : unformatted) { try { formatted.add(generateResponse(o).get()); } catch (JedisDataException e) { formatted.add(e); } } return formatted; } else { return java.util.Collections.<Object> emptyList(); } }
@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"); }
@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()); }
@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 } }
@Test public void sentinelMonitor() { Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); try { // monitor new master String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, master.getPort(), 1); assertEquals("OK", result); // already monitored try { j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, master.getPort(), 1); fail(); } catch (JedisDataException e) { // pass } } finally { j.close(); } }
@Test public void sentinelRemove() { Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); try { ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP, master.getPort(), 1); String result = j.sentinelRemove(REMOVE_MASTER_NAME); assertEquals("OK", result); // not exist try { result = j.sentinelRemove(REMOVE_MASTER_NAME); assertNotEquals("OK", result); fail(); } catch (JedisDataException e) { // pass } } finally { j.close(); } }
public List<Object> exec() { client.exec(); client.getAll(1); // Discard all but the last reply inTransaction = false; List<Object> unformatted = client.getObjectMultiBulkReply(); if (unformatted == null) { return null; } List<Object> formatted = new ArrayList<Object>(); for (Object o : unformatted) { try { formatted.add(generateResponse(o).get()); } catch (JedisDataException e) { formatted.add(e); } } return formatted; }
private static void processError(final RedisInputStream is) { String message = is.readLine(); // TODO: I'm not sure if this is the best way to do this. // Maybe Read only first 5 bytes instead? if (message.startsWith(MOVED_RESPONSE)) { String[] movedInfo = parseTargetHostAndSlot(message); throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], Integer.valueOf(movedInfo[2])), Integer.valueOf(movedInfo[0])); } else if (message.startsWith(ASK_RESPONSE)) { String[] askInfo = parseTargetHostAndSlot(message); throw new JedisAskDataException(message, new HostAndPort(askInfo[1], Integer.valueOf(askInfo[2])), Integer.valueOf(askInfo[0])); } else if (message.startsWith(CLUSTERDOWN_RESPONSE)) { throw new JedisClusterException(message); } throw new JedisDataException(message); }
public T get() { // if response has dependency response and dependency is not built, // build it first and no more!! if (dependency != null && dependency.set && !dependency.built) { dependency.build(); } if (!set) { throw new JedisDataException( "Please close pipeline or multi block before calling this method."); } if (!built) { build(); } if (exception != null) { throw exception; } return response; }
public List<Object> exec() { // Discard QUEUED or ERROR client.getMany(getPipelinedResponseLength()); client.exec(); inTransaction = false; List<Object> unformatted = client.getObjectMultiBulkReply(); if (unformatted == null) { return null; } List<Object> formatted = new ArrayList<Object>(); for (Object o : unformatted) { try { formatted.add(generateResponse(o).get()); } catch (JedisDataException e) { formatted.add(e); } } return formatted; }
/** * Synchronize pipeline by reading all responses. This operation close the pipeline. Whenever * possible try to avoid using this version and use Pipeline.sync() as it won't go through all the * responses and generate the right response type (usually it is a waste of time). * @return A list of all the responses in the order you executed them. */ public List<Object> syncAndReturnAll() { if (getPipelinedResponseLength() > 0) { List<Object> unformatted = client.getMany(getPipelinedResponseLength()); List<Object> formatted = new ArrayList<Object>(); for (Object o : unformatted) { try { formatted.add(generateResponse(o).get()); } catch (JedisDataException e) { formatted.add(e); } } return formatted; } else { return java.util.Collections.<Object> emptyList(); } }
/** * Handle jedisException, write log and return whether the connection is broken. */ protected boolean handleJedisException(JedisException jedisException) { if (jedisException instanceof JedisConnectionException) { logger.error("Redis connection " + jedisPool.getAddress() + " lost.", jedisException); } else if (jedisException instanceof JedisDataException) { if ((jedisException.getMessage() != null) && (jedisException.getMessage().indexOf("READONLY") != -1)) { logger.error("Redis connection " + jedisPool.getAddress() + " are read-only slave.", jedisException); } else { // dataException, isBroken=false return false; } } else { logger.error("Jedis exception happen.", jedisException); } return true; }
/** * 执行Lua Script, 如果Redis服务器上还没装载Script则自动装载并重试。 * keys与args不允许为null. */ public Object execute(final List<String> keys, final List<String> args) throws IllegalArgumentException { Preconditions.checkNotNull(keys, "keys can't be null."); Preconditions.checkNotNull(args, "args can't be null."); return jedisTemplate.execute(new JedisAction<Object>() { @Override public Object action(Jedis jedis) { try { return jedis.evalsha(sha1, keys, args); } catch (JedisDataException e) { logger.warn( "Script {} is not loaded in server yet or the script is wrong, try to reload and run it again.", script, e); return jedis.eval(script, keys, args); } } }); }
/** * 原子释放锁 * * @param key * @param value * @return */ public Long releaseNoneReentrantLock(final String key, final String value) { if (RedisConstants.isInUse()) { return getTemplate().executeWrite(new JedisCallBackHandler<Long>() { public Long invoke(Jedis jedis) { Script script = ScriptCache.getScript("releaseNoneReentrantLock"); String sha = script.getSha(); if (null == sha) { sha = jedis.scriptLoad(script.getLuaScript()); script.setSha(sha); } try { return (Long) jedis.evalsha(sha, 2, key, value); } catch (JedisDataException e) { if (e.getMessage().equals("NOSCRIPT No matching script. Please use EVAL.")) { jedis.scriptLoad(script.getLuaScript()); return (Long) jedis.evalsha(sha, 2, key, value); } return null; } } }); } else { return null; } }
/** * 获取全局锁 * * @param key * @param value * @param ttl * @return */ public Long getGlobalReentrantLock(final String key, final String value, final long level, final int ttl) { if (RedisConstants.isInUse()) { return getTemplate().executeWrite(new JedisCallBackHandler<Long>() { public Long invoke(Jedis jedis) { Script script = ScriptCache.getScript("getGlobalReentrantLock"); String sha = script.getSha(); if (null == sha) { sha = jedis.scriptLoad(script.getLuaScript()); script.setSha(sha); } try { return (Long) jedis.evalsha(sha, 4, key, value, String.valueOf(level), String.valueOf(ttl)); } catch (JedisDataException e) { if (e.getMessage().equals("NOSCRIPT No matching script. Please use EVAL.")) { jedis.scriptLoad(script.getLuaScript()); return (Long) jedis.evalsha(sha, 4, key, value, String.valueOf(level), String.valueOf(ttl)); } return null; } } }); } else { return null; } }
/** * 释放全局锁 * * @param key * @param value * @return */ public Long releaseGlobalReentrantLock(final String key, final String value, final long level) { if (RedisConstants.isInUse()) { return getTemplate().executeWrite(new JedisCallBackHandler<Long>() { public Long invoke(Jedis jedis) { Script script = ScriptCache.getScript("releaseGlobalReentrantLock"); String sha = script.getSha(); if (null == sha) { sha = jedis.scriptLoad(script.getLuaScript()); script.setSha(sha); } try { return (Long) jedis.evalsha(sha, 3, key, value, String.valueOf(level)); } catch (JedisDataException e) { if (e.getMessage().equals("NOSCRIPT No matching script. Please use EVAL.")) { jedis.scriptLoad(script.getLuaScript()); return (Long) jedis.evalsha(sha, 3, key, value, String.valueOf(level)); } return null; } } }); } else { return null; } }
/** * 释放请求链所有锁 * * @param key * @return */ public Long releaseChainLock(String chainId) { if (RedisConstants.isInUse()) { return getTemplate().executeWrite(new JedisCallBackHandler<Long>() { public Long invoke(Jedis jedis) { Script script = ScriptCache.getScript("releaseChainLock"); String sha = script.getSha(); if (null == sha) { sha = jedis.scriptLoad(script.getLuaScript()); script.setSha(sha); } try { return (Long) jedis.evalsha(sha, 1, chainId); } catch (JedisDataException e) { if (e.getMessage().equals("NOSCRIPT No matching script. Please use EVAL.")) { jedis.scriptLoad(script.getLuaScript()); return (Long) jedis.evalsha(sha, 1, chainId); } return null; } } }); } else { return null; } }
/** * 排队获取锁 * * @param key * @return */ public Long queueGetGlobalReentrantLock(final String key, final String value, final long level, final int ttl) { if (RedisConstants.isInUse()) { return getTemplate().executeWrite(new JedisCallBackHandler<Long>() { public Long invoke(Jedis jedis) { Script script = ScriptCache.getScript("queueGetGlobalReentrantLock"); String sha = script.getSha(); if (null == sha) { sha = jedis.scriptLoad(script.getLuaScript()); script.setSha(sha); } try { return (Long) jedis.evalsha(sha, 4, key, value, String.valueOf(level), String.valueOf(ttl)); } catch (JedisDataException e) { if (e.getMessage().equals("NOSCRIPT No matching script. Please use EVAL.")) { jedis.scriptLoad(script.getLuaScript()); return (Long) jedis.evalsha(sha, 4, key, value, String.valueOf(level), String.valueOf(ttl)); } return null; } } }); } else { return null; } }
/** * 解锁 * * @param key * @return */ public Long unLockGlobalReentrantLock(final String key, final String value, final long level) { if (RedisConstants.isInUse()) { return getTemplate().executeWrite(new JedisCallBackHandler<Long>() { public Long invoke(Jedis jedis) { Script script = ScriptCache.getScript("unLockGlobalReentrantLock"); String sha = script.getSha(); if (null == sha) { sha = jedis.scriptLoad(script.getLuaScript()); script.setSha(sha); } try { return (Long) jedis.evalsha(sha, 3, key, value, String.valueOf(level)); } catch (JedisDataException e) { if (e.getMessage().equals("NOSCRIPT No matching script. Please use EVAL.")) { jedis.scriptLoad(script.getLuaScript()); return (Long) jedis.evalsha(sha, 3, key, value, String.valueOf(level)); } return null; } } }); } else { return null; } }
/** * 唤醒得锁 * * @param key * @return */ public Long callGetGlobalReentrantLock(final String key, final String value, final int ttl) { if (RedisConstants.isInUse()) { return getTemplate().executeWrite(new JedisCallBackHandler<Long>() { public Long invoke(Jedis jedis) { Script script = ScriptCache.getScript("callGetGlobalReentrantLock"); String sha = script.getSha(); if (null == sha) { sha = jedis.scriptLoad(script.getLuaScript()); script.setSha(sha); } try { return (Long) jedis.evalsha(sha, 3, key, value, String.valueOf(ttl)); } catch (JedisDataException e) { if (e.getMessage().equals("NOSCRIPT No matching script. Please use EVAL.")) { jedis.scriptLoad(script.getLuaScript()); return (Long) jedis.evalsha(sha, 3, key, value, String.valueOf(ttl)); } return null; } } }); } else { return null; } }