public Jedis get() throws JedisException { Jedis jedis = context.get(); if (jedis != null) { return jedis; } try { jedis = jedisPool.getResource(); } catch (JedisException e) { if (jedis != null) { jedis.close(); } throw e; } context.set(jedis); if (logger.isTraceEnabled()) { logger.trace(">>get a redis conn[{}],Host:{}", jedis.toString(), jedis.getClient().getHost()); } return jedis; }
public ShardedJedis get() throws JedisException { ShardedJedis jedis = context.get(); if (jedis != null) { return jedis; } try { jedis = jedisPool.getResource(); } catch (JedisException e) { if (jedis != null) { jedis.close(); } throw e; } context.set(jedis); if (logger.isTraceEnabled()) { logger.trace(">>get a redis conn[{}]", jedis.toString()); } return jedis; }
@Override public Long zadd(final String key, final Map<String, Double> scoreMembers) { try { Double score = null; String member = null; List<ZsetPair> scoresmembers = new ArrayList<ZsetPair>((scoreMembers.size() - 1)*2); for (String m : scoreMembers.keySet()) { if (m == null) { member = m; score = scoreMembers.get(m); continue; } scoresmembers.add(new ZsetPair(m, scoreMembers.get(m))); } return redis.zadd(key, new ZsetPair(member, score), (ZsetPair[])scoresmembers.toArray()); } catch (Exception e) { throw new JedisException(e); } }
@Override public String remove(@NotNull String key) { if (key == null) { throw new IllegalArgumentException("Cannot remove null key"); } String rKey = redisKey(storeName, key); try (Jedis jedis = pool.getResource()) { String previousValue = jedis.get(rKey); jedis.del(rKey); return previousValue; } catch (JedisException e) { redisIsHealthy = false; String msg = String.format("Unable to remove key %s (Redis key %s)", key, rKey); LOG.error(msg); throw new RuntimeException(msg, e); } }
@Override public String get(@NotNull String key) { if (key == null) { throw new IllegalArgumentException("Cannot get null key"); } String rKey = redisKey(storeName, key); try (Jedis jedis = pool.getResource()) { return jedis.get(rKey); } catch (JedisException e) { redisIsHealthy = false; String msg = String.format("Unable to get key %s (Redis key %s)", key, rKey); LOG.error(msg); throw new RuntimeException(e); } }
/** * Execute with a call back action with result in pipeline. */ public List<Object> execute(PipelineAction pipelineAction) throws JedisException { Jedis jedis = null; boolean broken = false; try { jedis = jedisPool.getResource(); Pipeline pipeline = jedis.pipelined(); pipelineAction.action(pipeline); return pipeline.syncAndReturnAll(); } catch (JedisException e) { broken = handleJedisException(e); throw e; } finally { closeResource(jedis, broken); } }
public JsonArray mget(String...keys) { try(Context context = mgetTimer.time()) { JsonArray results=array(); try(Jedis resource = jedisPool.getResource()) { byte[][] byteKeys = Arrays.stream(keys).map(key -> key(key)).toArray(size -> new byte[size][]); List<byte[]> redisResults = resource.mget(byteKeys); if(redisResults!=null) { for(byte[] blob:redisResults) { if(blob != null) { // some results will be null results.add(parser.parseObject(new String(CompressionUtils.decompress(blob), utf8))); } } } } catch (JedisException e) { // make sure we can find back jedis related stuff in kibana throw new IllegalStateException("problem connecting to jedis", e); } notFoundMeter.mark(); return results; } }
public ShardedJedis get() throws JedisException { ShardedJedis jedis = context.get(); if(jedis != null)return jedis; try { jedis = jedisPool.getResource(); } catch (JedisException e) { if(jedis!=null){ jedis.close(); } throw e; } context.set(jedis); if(logger.isTraceEnabled()){ logger.trace(">>get a redis conn[{}]",jedis.toString()); } return jedis; }
public static boolean updateKafkaLogEvent(int unixtime, final String event){ Date date = new Date(unixtime*1000L); final String dateStr = DateTimeUtil.formatDate(date ,DATE_FORMAT_PATTERN); final String dateHourStr = DateTimeUtil.formatDate(date ,YYYY_MM_DD_HH); boolean commited = new RedisCommand<Boolean>(jedisPool) { @Override protected Boolean build() throws JedisException { String keyD = MONITOR_PREFIX+dateStr; String keyH = MONITOR_PREFIX+dateHourStr; Pipeline p = jedis.pipelined(); p.hincrBy(keyD, "e:"+event , 1L); p.expire(keyD, AFTER_4_DAYS); p.hincrBy(keyH, "e:"+event , 1L); p.expire(keyH, AFTER_2_DAYS); p.sync(); return true; } }.execute(); return commited; }
@Override public PooledObject<Jedis> makeObject() throws Exception { final HostAndPort hostAndPort = this.hostAndPort.get(); JaRedis.Builder builder = new JaRedis.Builder(); builder .host(hostAndPort.getHost()) .port(hostAndPort.getPort()) .connectionTimeout(connectionTimeout) .soTimeout(soTimeout); Jedis jedis = builder.build(); try { jedis.connect(); if (null != this.password) { jedis.auth(this.password); } if (database != 0) { jedis.select(database); } if (clientName != null) { jedis.clientSetname(clientName); } } catch (JedisException je) { jedis.close(); throw je; } return new DefaultPooledObject<>(jedis); }
/** * 获取资源 * * @return * @throws JedisException */ public static Jedis getResource() throws JedisException { Jedis jedis = null; try { jedis = jedisPool.getResource(); // logger.debug("getResource.", jedis); } catch (JedisException e) { logger.warn("getResource.", e); returnBrokenResource(jedis); throw e; } return jedis; }
@Override public Jedis getConnection() { // In antirez's redis-rb-cluster implementation, // getRandomConnection always return valid connection (able to // ping-pong) // or exception if all connections are invalid List<JedisPool> pools = cache.getShuffledNodesPool(); for (JedisPool pool : pools) { Jedis jedis = null; try { jedis = pool.getResource(); if (jedis == null) { continue; } String result = jedis.ping(); if (result.equalsIgnoreCase("pong")) { return jedis; } jedis.close(); } catch (JedisException ex) { if (jedis != null) { jedis.close(); } } } throw new JedisNoReachableClusterNodeException("No reachable node in cluster"); }
@Override public PooledObject<Jedis> makeObject() throws Exception { final HostAndPort hostAndPort = this.hostAndPort.get(); final Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort(), connectionTimeout, soTimeout, password, database, ssl, sslSocketFactory, sslParameters, hostnameVerifier); try { jedis.connect(); //if (password != null && !password.isEmpty()) { // jedis.auth(password); //} //if (database != 0) { // jedis.select(database); //} if (clientName != null) { String reply = jedis.clientSetname(clientName); if (!"OK".equalsIgnoreCase(reply)) { logger.info("reply={}",reply); } } } catch (JedisException je) { jedis.close(); throw je; } return new DefaultPooledObject<Jedis>(jedis); }
/** * @deprecated starting from Jedis 3.0 this method will not be exposed. Resource * cleanup should be done using @see * {@link redis.clients.jedis.Jedis#close()} */ @Override @Deprecated public void returnResource(final Jedis resource) { if (resource != null) { try { resource.resetState(); returnResourceObject(resource); } catch (Exception e) { returnBrokenResource(resource); throw new JedisException("Could not return the resource to the pool", e); } } }
public static byte[] encode(final String str) { try { if (str == null) { throw new JedisDataException("value sent to redis cannot be null"); } return str.getBytes(Protocol.CHARSET); } catch (UnsupportedEncodingException e) { throw new JedisException(e); } }
public static String encode(final byte[] data) { try { return new String(data, Protocol.CHARSET); } catch (UnsupportedEncodingException e) { throw new JedisException(e); } }
public T getResource() { try { return internalPool.borrowObject(); } catch (NoSuchElementException nse) { if (null == nse.getCause()) { // The exception was caused by an exhausted pool throw new JedisExhaustedPoolException("Could not get a resource since the pool is exhausted", nse); } // Otherwise, the exception was caused by the implemented activateObject() or // ValidateObject() throw new JedisException("Could not get a resource from the pool", nse); } catch (Exception e) { throw new JedisConnectionException("Could not get a resource from the pool", e); } }
/** * @deprecated starting from Jedis 3.0 this method will not be exposed. Resource * cleanup should be done using @see * {@link io.jedis#close()} */ @Deprecated public void returnResourceObject(final T resource) { if (resource == null) { return; } try { internalPool.returnObject(resource); } catch (Exception e) { throw new JedisException("Could not return the resource to the pool", e); } }
protected void returnBrokenResourceObject(final T resource) { try { internalPool.invalidateObject(resource); } catch (Exception e) { throw new JedisException("Could not return the resource to the pool", e); } }
protected void closeInternalPool() { try { internalPool.close(); } catch (Exception e) { throw new JedisException("Could not destroy the pool", e); } }
public void addObjects(int count) { try { for (int i = 0; i < count; i++) { this.internalPool.addObject(); } } catch (Exception e) { throw new JedisException("Error trying to add idle objects", e); } }
@Test(expected = JedisException.class) public void checkPoolOverflow() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(1); config.setBlockWhenExhausted(false); JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort()); Jedis jedis = pool.getResource(); jedis.auth("foobared"); jedis.set("foo", "0"); Jedis newJedis = pool.getResource(); newJedis.auth("foobared"); newJedis.incr("foo"); }
private static void assertNodeRecognizedStatus(Jedis node, String targetNodeId, boolean shouldRecognized, int timeoutMs) { int sleepInterval = 100; for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) { boolean known = isKnownNode(node, targetNodeId); if (shouldRecognized == known) return; try { Thread.sleep(sleepInterval); } catch (InterruptedException e) { } } throw new JedisException("Node recognize check error"); }
@Test public void shouldNotUpdateDbIndexIfSelectFails() throws URISyntaxException { long currentDb = jedis.getDB(); try { int invalidDb = -1; jedis.select(invalidDb); fail("Should throw an exception if tried to select invalid db"); } catch (JedisException e) { assertEquals(currentDb, jedis.getDB().intValue()); } }
@Test(expected = JedisException.class) public void testIfPoolConfigAppliesToClusterPools() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(0); config.setMaxWaitMillis(DEFAULT_TIMEOUT); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", config); jc.set("52", "poolTestValue"); }
private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) { int sleepInterval = 100; for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) { boolean isHandshaking = isAnyNodeHandshaking(node); if (!isHandshaking) return; try { Thread.sleep(sleepInterval); } catch (InterruptedException e) { } } throw new JedisException("Node handshaking is not ended"); }
@Test(expected = JedisException.class) public void checkPoolOverflow() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(1); config.setBlockWhenExhausted(false); ShardedJedisPool pool = new ShardedJedisPool(config, shards); ShardedJedis jedis = pool.getResource(); jedis.set("foo", "0"); ShardedJedis newJedis = pool.getResource(); newJedis.incr("foo"); }
/** * * 验证连接是否可用 * * @param obj 对象 * @return boolean 返回值 */ public boolean validateObject(final Object obj) { if (obj instanceof Jedis) { final Jedis jedis = (Jedis) obj; try { return jedis.isConnected() && jedis.ping().equals("PONG"); } catch (JedisException e) { logger.error(e.getMessage()); return false; } } else { return false; } }
/** * * 功能描述: 销毁所有池 * */ public void destroy() { for (DefaultJedisPool jedisPool : pools) { try { jedisPool.destroy(); } catch (JedisException e) { logger.error(e.getMessage()); } } }
/** * 获取资源 * @return * @throws JedisException */ public static Jedis getResource() throws JedisException { Jedis jedis = null; try { jedis = jedisPool.getResource(); // logger.debug("getResource.", jedis); } catch (JedisException e) { logger.warn("getResource.", e); returnBrokenResource(jedis); throw e; } return jedis; }
/** * @deprecated starting from Jedis 3.0 this method won't exist. Resouce cleanup should be done * using @see {@link redis.clients.jedis.Jedis#close()} */ @Deprecated public void returnResource(final Jedis resource) { if (resource != null) { try { resource.resetState(); returnResourceObject(resource); } catch (Exception e) { returnBrokenResource(resource); throw new JedisException("Could not return the resource to the pool", e); } } }
/** * Synchronously save the DB on disk, then shutdown the server. * <p> * Stop all the clients, save the DB, then quit the server. This commands makes sure that the DB * is switched off without the lost of any data. This is not guaranteed if the client uses simply * {@link #save() SAVE} and then {@link #quit() QUIT} because other clients may alter the DB data * between the two commands. * @return Status code reply on error. On success nothing is returned since the server quits and * the connection is closed. */ public String shutdown() { client.shutdown(); String status; try { status = client.getStatusCodeReply(); } catch (JedisException ex) { status = null; } return status; }
/** * @deprecated starting from Jedis 3.0 this method won't exist. Resouce cleanup should be done * using @see {@link redis.clients.jedis.Jedis#close()} */ @Deprecated public void returnResourceObject(final T resource) { if (resource == null) { return; } try { internalPool.returnObject(resource); } catch (Exception e) { throw new JedisException("Could not return the resource to the pool", e); } }
public void addObjects(int count) { try { for (int i = 0; i < count ; i++) { this.internalPool.addObject(); } } catch (Exception e) { throw new JedisException("Error trying to add idle objects", e); } }
protected <T> T execute(CallBack<T> callback) { Jedis jedis = null; try { jedis = pool.getResource(); return callback.invoke(jedis); } catch (JedisException e) { logger.error("jedis pool get resource error:{}", e); } finally { if (null != jedis) { jedis.close(); } } return null; }