public static void main(String[] args) { JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost"); Jedis jedis = null; try { jedis = pool.getResource(); /// ... do stuff here ... for example jedis.set("foo", "bar"); String foobar = jedis.get("foo"); System.out.println("foobar=" + foobar); jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike"); Set<String> sose = jedis.zrange("sose", 0, -1); jedis.watch("foo"); Transaction t = jedis.multi(); t.set("foo", "bar"); t.exec(); } finally { if (jedis != null) { jedis.close(); } } /// ... when closing your application: pool.destroy(); // Jedis jedis = new Jedis("localhost"); // //jedis.set("foo", "bar"); // String value = jedis.get("foo"); // System.out.println("value=" + value); }
protected void initRedis(String host, int port) { JedisPool pool = new JedisPool(new JedisPoolConfig(), host, port); jedis = pool.getResource(); jedis.connect(); jedis.getClient().setTimeoutInfinite(); jedis.flushAll(); }
/** Try lock with value */ public Boolean tryLock() { if (isTimeout()) { return true; } Jedis jedis = null; try { jedis = pool.getResource(); String newHoldValue = identity + getTimestamp(); String result = jedis.set(key, newHoldValue, "NX", "PX", expireTime); if ("OK".equals(result)) { lastHoldValue = newHoldValue; return true; } return false; } catch (JedisConnectionException e) { if (jedis != null) { pool.returnBrokenResource(jedis); } updateLastFailedTime(); throw e; } finally { if (jedis != null) { pool.returnResource(jedis); } } }
public synchronized void recover() { logger.debug("recover..."); if (status.equals(STATUS.READY)) { logger.debug("The redis's status is ready, return void."); return; } jedisPool.returnBrokenResource(subscriber); subscriber = null; subscriber = jedisPool.getResource(); status = STATUS.INIT; new Thread( new Runnable() { @Override public void run() { try { logger.debug("重新预订阅主题..."); subscriber.subscribe(listener, "~~~~~~~"); } catch (Exception e) { logger.error(e.getMessage(), e); logger.error("预订阅退出..."); status = STATUS.BROKEN; } } }) .start(); status = STATUS.READY; logger.debug("recover done"); }
private void deferExpired() { for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) { JedisPool jedisPool = entry.getValue(); try { Jedis jedis = jedisPool.getResource(); try { RedisRegistryUtil.publishToJedis(jedis, getRegistered(), root, expirePeriod); if (admin) { clean(jedis); } if (!replicate) { break; // 如果服务器端已同步数据,只需写入单台机器 } } finally { jedisPool.returnResource(jedis); } } catch (Throwable t) { logger.warn( "Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t); } } }
public static void main(String[] args) { JedisPool jedisPool = new JedisPool("localhost"); try { Jedis jedis = jedisPool.getResource(); String result = jedis.get("msg"); System.out.println(result); jedis.set("msg_java", "Hello Java"); jedisPool.returnResource(jedis); String key, value; Scanner sc = new Scanner(System.in); do { System.out.println("veuillez entrer la clé"); key = sc.next(); System.out.println("veuillez entrer la valeur"); value = sc.next(); jedis.set(key, value); jedisPool.returnResource(jedis); System.out.println(key + " " + value); System.out.println(key + " " + jedis.get(key)); } while (!key.equals("")); sc.close(); } finally { jedisPool.destroy(); } }
public static void getBackupSummary(String id, String bkpId) throws Exception { SalesforceOrg org = dbUtils.findOrganizationById(id); for (Backup bkp : dbUtils.backupsForOrg(org.getOrgId())) { if (bkpId.equalsIgnoreCase((bkp.getId()))) { JedisPool pool = null; Jedis jedis = null; try { pool = poolFactory.getPool(); jedis = pool.getResource(); response.setContentTypeIfNotSet("application/json"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Inclusion.NON_NULL); renderJSON( objectMapper.writeValueAsString( DifferenceUtils.summarizeDifferences( jedis.hget(bkp.getGitVersion(), "changes")))); } finally { if (pool != null && jedis != null) { pool.returnResource(jedis); } } break; } } renderJSON("{}"); }
private Map<String, Double> getPrices(JedisPool pool, boolean openingPrices) { Map<String, Double> prices = new HashMap<String, Double>(); Jedis jedis = null; try { jedis = pool.getResource(); String[] keys = new String[TICKER_SYMBOLS.length]; int i = 0; for (String symbol : TICKER_SYMBOLS) { symbol = (openingPrices) ? symbol + ".start" : symbol; keys[i++] = "stock." + symbol; } List<String> values = jedis.mget(keys); i = 0; for (String value : values) { if (value == null) { throw new IllegalStateException( "Redis should contain a value for stock " + TICKER_SYMBOLS[i++]); } prices.put(TICKER_SYMBOLS[i++], Double.valueOf(value)); } pool.returnResource(jedis); } catch (RuntimeException re) { if (jedis != null) pool.returnBrokenResource(jedis); } return prices; }
public static void main(String[] args) throws Exception { JedisPool pool = JedisPoolFactory.createJedisPool( JedisUtils.DEFAULT_HOST, JedisUtils.DEFAULT_PORT, JedisUtils.DEFAULT_TIMEOUT, 1); try { JobDispatcher dispatcher = new JobDispatcher("ss", pool); JobStatistics statistics = new JobStatistics("ss", pool); startPrintStatistics(statistics); dispatcher.start(); System.out.println("Hit enter to stop."); while (true) { char c = (char) System.in.read(); if (c == '\n') { System.out.println("Shuting down"); dispatcher.stop(); stopPrintStatistics(); return; } } } finally { pool.destroy(); } }
private void deferExpired() { for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) { JedisPool jedisPool = entry.getValue(); try { Jedis jedis = jedisPool.getResource(); try { for (Node node : new HashSet<Node>(getRegistered())) { String key = NodeRegistryUtils.getNodeTypePath(clusterName, node.getNodeType()); if (jedis.hset( key, node.toFullString(), String.valueOf(SystemClock.now() + expirePeriod)) == 1) { jedis.publish(key, Constants.REGISTER); } } if (lock.acquire(jedis)) { clean(jedis); } if (!replicate) { break; // 如果服务器端已同步数据,只需写入单台机器 } } finally { jedis.close(); } } catch (Throwable t) { LOGGER.warn( "Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t); } } }
@Test public void create() throws Exception { Map<String, String> attrs = ImmutableMap.of("x", "X"); Map<String, String> attrsToSave = ImmutableMap.of( "x", "X", "_accessedAt", "2", "_createdAt", "1", "_savedAt", "3"); new MockUnit(JedisPool.class, Session.class) .expect( unit -> { Session session = unit.get(Session.class); expect(session.id()).andReturn("1234"); expect(session.attributes()).andReturn(attrs); expect(session.createdAt()).andReturn(1L); expect(session.accessedAt()).andReturn(2L); expect(session.savedAt()).andReturn(3L); }) .expect( unit -> { Jedis jedis = unit.mock(Jedis.class); expect(jedis.hmset("sessions:1234", attrsToSave)).andReturn("sessions:1234"); expect(jedis.expire("sessions:1234", 1800)).andReturn(1L); jedis.close(); JedisPool pool = unit.get(JedisPool.class); expect(pool.getResource()).andReturn(jedis); }) .run( unit -> { new RedisSessionStore(unit.get(JedisPool.class), "sessions", "30m") .create(unit.get(Session.class)); }); }
@Override public String call() { Meter job_process_rate = metrics.getMetrics().meter(Constants.JOBS_PROCESS_RATE); JedisPool pool = null; Jedis jedis = null; try { pool = redis.getRedisConnectionPool(); jedis = pool.getResource(); List<String> payload = jedis.brpop(0, Constants.JOBS_QUEUE); // TODO perform some processing on the payload here // Mark processing of the job here in the metrics library // These metrics are aggregated and sent to graphite job_process_rate.mark(); } catch (JedisConnectionException e) { // returnBrokenResource when the state of the object is // unrecoverable if (null != jedis) { jedis.close(); } } finally { if (null != jedis) { jedis.close(); } } return "Done processing Callable Task "; }
@Test(expected = IllegalStateException.class) public void shouldCloseJedisOnGetErr() throws Exception { new MockUnit(JedisPool.class, Session.Builder.class) .expect( unit -> { Session.Builder sb = unit.get(Session.Builder.class); expect(sb.sessionId()).andReturn("1234"); }) .expect( unit -> { Jedis jedis = unit.mock(Jedis.class); expect(jedis.hgetAll("sessions:1234")) .andThrow(new IllegalStateException("intentional err")); jedis.close(); JedisPool pool = unit.get(JedisPool.class); expect(pool.getResource()).andReturn(jedis); }) .run( unit -> { new RedisSessionStore(unit.get(JedisPool.class), "sessions", "30m") .get(unit.get(Session.Builder.class)); }); }
@Test public void getEmptyExpired() throws Exception { Map<String, String> attrs = Collections.emptyMap(); new MockUnit(JedisPool.class, Session.Builder.class) .expect( unit -> { Session.Builder sb = unit.get(Session.Builder.class); expect(sb.sessionId()).andReturn("1234"); }) .expect( unit -> { Jedis jedis = unit.mock(Jedis.class); expect(jedis.hgetAll("sessions:1234")).andReturn(attrs); jedis.close(); JedisPool pool = unit.get(JedisPool.class); expect(pool.getResource()).andReturn(jedis); }) .run( unit -> { assertEquals( null, new RedisSessionStore(unit.get(JedisPool.class), "sessions", "30m") .get(unit.get(Session.Builder.class))); }); }
@Test public void testCloseable() throws IOException { Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); JedisCluster jc = null; try { jc = new JedisCluster(jedisClusterNode); jc.set("51", "foo"); } finally { if (jc != null) { jc.close(); } } Iterator<JedisPool> poolIterator = jc.getClusterNodes().values().iterator(); while (poolIterator.hasNext()) { JedisPool pool = poolIterator.next(); try { pool.getResource(); fail("JedisCluster's internal pools should be already destroyed"); } catch (JedisConnectionException e) { // ok to go... } } }
public void destroy() { super.destroy(); try { expireFuture.cancel(true); } catch (Throwable t) { logger.warn(t.getMessage(), t); } try { for (RedisRegistryNotifier notifier : notifiers.values()) { notifier.shutdown(); } } catch (Throwable t) { logger.warn(t.getMessage(), t); } for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) { JedisPool jedisPool = entry.getValue(); try { jedisPool.destroy(); } catch (Throwable t) { logger.warn( "Failed to destroy the redis registry client. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t); } } }
public void doSubscribe(final URL url, final NotifyListener listener) { String service = RedisRegistryUtil.toServicePath(url, root); RedisRegistryNotifier notifier = notifiers.get(service); if (notifier == null) { RedisRegistryNotifier newNotifier = new RedisRegistryNotifier(service, this); notifiers.putIfAbsent(service, newNotifier); notifier = notifiers.get(service); if (notifier == newNotifier) { notifier.start(); } } boolean success = false; RpcException exception = null; for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) { JedisPool jedisPool = entry.getValue(); try { Jedis jedis = jedisPool.getResource(); try { if (service.endsWith(Constants.ANY_VALUE)) { admin = true; Set<String> keys = jedis.keys(service); if (keys != null && keys.size() > 0) { Map<String, Set<String>> serviceKeys = RedisRegistryUtil.getServiceKeys(keys, root); for (Set<String> sk : serviceKeys.values()) { doNotify(jedis, sk, url, Arrays.asList(listener)); } } } else { doNotify( jedis, jedis.keys(service + Constants.PATH_SEPARATOR + Constants.ANY_VALUE), url, Arrays.asList(listener)); } success = true; break; // 只需读一个服务器的数据 } finally { jedisPool.returnResource(jedis); } } catch (Throwable t) { // 尝试下一个服务器 exception = new RpcException( "Failed to subscribe service from redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t); } } if (exception != null) { if (success) { logger.warn(exception.getMessage(), exception); } else { throw exception; } } }
/** * Add the specified member to the set value stored at key. If member is already a member of the * set no operation is performed. If key does not exist a new set with the specified member as * sole member is created. If the key exists but does not hold a set value an error is returned. * * <p>Time complexity O(1) * * @param key * @param member * @return Integer reply, specifically: 1 if the new element was added 0 if the element was * already a member of the set */ public long sadd(String key, String member) { Jedis jedis = jedisPool.getResource(); try { return jedis.sadd(key, member); } finally { jedisPool.returnResource(jedis); } }
/** * Set a timeout on the specified key. After the timeout the key will be automatically deleted by * the server. A key with an associated timeout is said to be volatile in Redis terminology. * * <p>Voltile keys are stored on disk like the other keys, the timeout is persistent too like all * the other aspects of the dataset. Saving a dataset containing expires and stopping the server * does not stop the flow of time as Redis stores on disk the time when the key will no longer be * available as Unix time, and not the remaining seconds. * * <p>Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire * set. It is also possible to undo the expire at all turning the key into a normal key using the * command. * * <p>Time complexity: O(1) * * @param key * @param seconds * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since * the key already has an associated timeout (this may happen only in Redis versions < 2.1.3, * Redis >= 2.1.3 will happily update the timeout), or the key does not exist. * @see <ahref="http://code.google.com/p/redis/wiki/ExpireCommand">ExpireCommand</a> */ public Long expire(final byte[] key, final int seconds) { Jedis jedis = jedisPool.getResource(); try { return jedis.expire(key, seconds); } finally { jedisPool.returnResource(jedis); } }
/** * GETSET is an atomic set this value and return the old value command. Set key to the string * value and return the old value stored at key. The string can't be longer than 1073741824 bytes * (1 GB). * * <p>Time complexity: O(1) * * @param key * @param value * @return Bulk reply */ public String getSet(final String key, final String value) { Jedis jedis = jedisPool.getResource(); try { return jedis.getSet(key, value); } finally { jedisPool.returnResource(jedis); } }
/** * Remove the specified keys. If a given key does not exist no operation is performed for this * key. The command returns the number of keys removed. * * <p>Time complexity: O(1) * * @param keys * @return Integer reply, specifically: an integer greater than 0 if one or more keys were removed * 0 if none of the specified key existed */ public Long del(final String... keys) { Jedis jedis = jedisPool.getResource(); try { return jedis.del(keys); } finally { jedisPool.returnResource(jedis); } }
/** * The command is exactly equivalent to the following group of commands: {@link #set(String, * String) SET} + {@link #expire(String, int) EXPIRE}. The operation is atomic. * * <p>Time complexity: O(1) * * @param key * @param seconds * @param value * @return Status code reply */ public String setex(final String key, final int seconds, final String value) { Jedis jedis = jedisPool.getResource(); try { return jedis.setex(key, seconds, value); } finally { jedisPool.returnResource(jedis); } }
/** * Remove the specified member from the set value stored at key. If member was not a member of the * set no operation is performed. If key does not hold a set value an error is returned. * * <p>Time complexity O(1) * * @param key * @param member * @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was * not a member of the set */ public Long srem(final String key, final String member) { Jedis jedis = jedisPool.getResource(); try { return jedis.srem(key, member); } finally { jedisPool.returnResource(jedis); } }
@Override protected void doSubscribe(Node node, NotifyListener listener) { List<NodeType> listenNodeTypes = node.getListenNodeTypes(); if (CollectionUtils.isEmpty(listenNodeTypes)) { return; } for (NodeType listenNodeType : listenNodeTypes) { String listenNodePath = NodeRegistryUtils.getNodeTypePath(clusterName, listenNodeType); Notifier notifier = notifiers.get(listenNodePath); if (notifier == null) { Notifier newNotifier = new Notifier(listenNodePath); notifiers.putIfAbsent(listenNodePath, newNotifier); notifier = notifiers.get(listenNodePath); if (notifier == newNotifier) { notifier.start(); } } boolean success = false; NodeRegistryException exception = null; for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) { JedisPool jedisPool = entry.getValue(); try { Jedis jedis = jedisPool.getResource(); try { doNotify( jedis, Collections.singletonList(listenNodePath), Collections.singletonList(listener)); success = true; break; // 只需读一个服务器的数据 } finally { jedis.close(); } } catch (Throwable t) { exception = new NodeRegistryException( "Failed to unregister node to redis registry. registry: " + entry.getKey() + ", node: " + node + ", cause: " + t.getMessage(), t); } } if (exception != null) { if (success) { LOGGER.warn(exception.getMessage(), exception); } else { throw exception; } } } }
public static void release(Jedis jedis, boolean isBroken) { if (jedis != null) { if (isBroken) { jedisPool.returnBrokenResource(jedis); } else { jedisPool.returnResource(jedis); } } }
@PreDestroy protected void destroy() { if (subscriber != null) { jedisPool.returnResource(subscriber); } if (publisher != null) { jedisPool.returnResource(publisher); } }
public void set(String value) { Jedis jedis = jedisPool.getResource(); try { jedis.set(name, value); jedisPool.returnResource(jedis); } catch (Exception e) { jedisPool.returnBrokenResource(jedis); } }
public void clear() { Jedis jedis = jedisPool.getResource(); try { jedis.del(name); jedisPool.returnResource(jedis); } catch (Exception e) { jedisPool.returnBrokenResource(jedis); } }
public String getLine(int lineNo) throws Exception { if (lineNo <= 0 || lineNo > mNumLines) { return null; } String line = null; Jedis jedis = pool_.getResource(); try { String lineNoStr = Integer.toString(lineNo); line = jedis.hget(lineNoStr, LINE_KEY); if (line == null) { RecordId lineId = getRecordId(lineNo); byte[] buffer = new byte[BLOCK_SIZE]; synchronized (mDataFile) { mDataFile.seek(lineId.pageNo() * BLOCK_SIZE); mDataFile.read(buffer); } ByteBuffer bb = ByteBuffer.wrap(buffer); int numRecords = bb.getInt(BLOCK_SIZE - INT_SIZE); int indexPos = BLOCK_SIZE - 3 * INT_SIZE; int curLineNo = lineNo - lineId.slotNo() + 1; String[] recordKeys = {PAGE_NO_KEY, SLOT_NO_KEY}; for (int i = 1; i < numRecords; i++, curLineNo++) { int offset = bb.getInt(indexPos); int len = bb.getInt(indexPos + INT_SIZE); ByteBuffer linebb = ByteBuffer.wrap(buffer, offset, len); byte[] lineBuf = new byte[linebb.remaining()]; linebb.get(lineBuf); String lineStr = new String(lineBuf); if (i == lineId.slotNo()) { line = lineStr; } // Store in cache lineNoStr = Integer.toString(curLineNo); jedis.hdel(lineNoStr, recordKeys); jedis.hset(lineNoStr, LINE_KEY, lineStr); indexPos -= 2 * INT_SIZE; } } if (line == null) { throw new Exception("LineServer: Could not find line on page"); } } catch (IOException ioe) { System.err.println("LineServer: IOException on line retrieval"); throw ioe; } finally { pool_.returnResource(jedis); } return line; }
@Override public void tearDown() throws Exception { Jedis jedis = jedisPool.getResource(); try { jedis.flushDB(); } finally { jedisPool.returnResource(jedis); } super.tearDown(); }