Java Code Examples for redis.clients.jedis.JedisPool#getResource()

The following examples show how to use redis.clients.jedis.JedisPool#getResource() . 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: JedisPoolTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void checkResourceIsCloseable() {
  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");
  } finally {
    jedis.close();
  }

  Jedis jedis2 = pool.getResource();
  try {
    assertEquals(jedis, jedis2);
  } finally {
    jedis2.close();
  }
}
 
Example 2
Source File: RedisRegistry.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isAvailable() {
    for (JedisPool jedisPool : jedisPools.values()) {
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                if (jedis.isConnected()) {
                    return true; // At least one single machine is available.
                }
            } finally {
                jedis.close();
            }
        } catch (Throwable t) {
        }
    }
    return false;
}
 
Example 3
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public boolean isAvailable() {
    for (JedisPool jedisPool : jedisPools.values()) {
        try {
            Jedis jedis = jedisPool.getResource();
            try {
            	if (jedis.isConnected()) {
                    return true; // 至少需单台机器可用
                }
            } finally {
                jedisPool.returnResource(jedis);
            }
        } catch (Throwable t) {
        }
    }
    return false;
}
 
Example 4
Source File: RedisRegistry.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public boolean isAvailable() {
    for (JedisPool jedisPool : jedisPools.values()) {
        Jedis jedis = jedisPool.getResource();
        boolean isBroken = false;
        try {
            if (jedis.isConnected()) {
                return true; // 至少需单台机器可用
            }
        } catch (JedisConnectionException e) {
            isBroken = true;
        } finally {
            if (isBroken) {
                jedisPool.returnBrokenResource(jedis);
            } else {
                jedisPool.returnResource(jedis);
            }
        }
    }
    return false;
}
 
Example 5
Source File: RedisUtils.java    From pinlater with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the connection from the connection pool and adds the wrapper catch/finally block for the
 * given function.
 *
 * This helper method saves the trouble of dealing with redis connection. When we got
 * JedisConnectionException, we will discard this connection. Otherwise, we return the connection
 * to the connection pool.
 *
 * @param jedisPool Jedis connection pool
 * @param redisDBNum Redis DB number (index) (if redisDBNum == -1, don't select a DB )
 * @param func    The function to execute inside the catch/finally block.
 * @return A Resp object, which is the return value of wrapped function.
 */
public static <Resp> Resp executeWithConnection(JedisPool jedisPool,
                                                int redisDBNum,
                                                Function<Jedis, Resp> func) {
  Preconditions.checkNotNull(jedisPool);
  Preconditions.checkNotNull(func);
  Jedis conn = null;
  boolean gotJedisConnException = false;
  try {
    conn = jedisPool.getResource();
    selectRedisDB(conn, redisDBNum);
    return func.apply(conn);
  } catch (JedisConnectionException e) {
    jedisPool.returnBrokenResource(conn);
    gotJedisConnException = true;
    throw e;
  } finally {
    if (conn != null && !gotJedisConnException) {
      jedisPool.returnResource(conn);
    }
  }
}
 
Example 6
Source File: JedisPoolFactory.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
/**
 * Gets or Creates a Jedis instance for the given connection string.
 * @param conStr Redis connection details, format is expected to be host:port or host:port:password_token
 * @return A Jedis connection if the connection succeeded, else the function will throw.
 */
public synchronized Jedis getOrCreateConn(String conStr)
{
    JedisPool pool = clientCache.get(conStr);
    if (pool == null) {
        String[] endpointParts = conStr.split(":");
        if (endpointParts.length == 2) {
            pool = getOrCreateCon(endpointParts[0], Integer.valueOf(endpointParts[1]));
        }
        else if (endpointParts.length == 3) {
            pool = getOrCreateCon(endpointParts[0], Integer.valueOf(endpointParts[1]), endpointParts[2]);
        }
        else {
            throw new IllegalArgumentException("Redis endpoint format error.");
        }

        clientCache.put(conStr, pool);
    }
    return pool.getResource();
}
 
Example 7
Source File: TestJedis.java    From DistributedCrawler with Apache License 2.0 5 votes vote down vote up
@Test
public void testMov(){
	JedisPool pool0 = new JedisPool(new Config(),"localhost",6377,1000,"940409",0);
	JedisPool pool1= new JedisPool(new Config(),"localhost",6377,1000,"940409",1);
	Jedis j0 = pool0.getResource();
	Jedis j1 = pool1.getResource();
	System.out.println(j1.get("1"));
	j0.set("1", "haha");
	j0.move("1", 1);
	System.out.println(j1.get("1"));
	
	
}
 
Example 8
Source File: TracingJedisPoolTest.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testPoolReturnsTracedJedis() {
  JedisPool pool = new TracingJedisPool(new TracingConfiguration.Builder(mockTracer).build());

  Jedis jedis = pool.getResource();
  assertEquals("OK", jedis.set("key", "value"));
  assertEquals("value", jedis.get("key"));

  jedis.close();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example 9
Source File: JedisPoolTest.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
@Test
public void checkCloseableConnections() throws Exception {
  JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000);
  Jedis jedis = pool.getResource();
  jedis.auth("foobared");
  jedis.set("foo", "bar");
  assertEquals("bar", jedis.get("foo"));
  jedis.close();
  pool.close();
  assertTrue(pool.isClosed());
}
 
Example 10
Source File: ExtractRegular.java    From HtmlExtractor with Apache License 2.0 5 votes vote down vote up
/**
 * 订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合
 */
private void subscribeRedis(final String redisHost, final int redisPort, final String serverUrl) {
    if (null == redisHost || redisPort < 1) {
        LOGGER.error("没有指定redis服务器配置!");
        return;
    }
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            String channel = "pr";
            LOGGER.info("redis服务器配置信息 host:" + redisHost + ",port:" + redisPort + ",channel:" + channel);
            while (true) {
                try {
                    JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort);
                    Jedis jedis = jedisPool.getResource();
                    LOGGER.info("redis守护线程启动");
                    jedis.subscribe(new ExtractRegularChangeRedisListener(serverUrl), new String[]{channel});
                    jedisPool.returnResource(jedis);
                    LOGGER.info("redis守护线程结束");
                    break;
                } catch (Exception e) {
                    LOGGER.info("redis未启动,暂停一分钟后重新连接");
                    try {
                        Thread.sleep(600000);
                    } catch (InterruptedException ex) {
                        LOGGER.error(ex.getMessage(), ex);
                    }
                }
            }
        }
    });
    thread.setDaemon(true);
    thread.setName("redis守护线程,用于动态加载抽取规则");
    thread.start();
}
 
Example 11
Source File: BaseCacheTemplate.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
private boolean testJedisPool(JedisPool jedisPool) {
	try {
		Jedis jedis = jedisPool.getResource();
		IOUtils.closeQuietly(jedis);
		return true;
	} catch (Exception ex) {
		LOG.warn("Acquisition J/Redis failed : " + ThrowableUtils.getRootCause(ex).getLocalizedMessage()
                   + " !!! Using backup ehcache for " + getClass());
	}
	return false;
}
 
Example 12
Source File: RedisTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void getRedisConnection() {
  JedisPoolConfig poolConfig = new JedisPoolConfig();
  pool = new JedisPool(poolConfig, URI.create(conf.uri), conf.connectionTimeout * MILLIS); // connectionTimeout value is in seconds
  String userInfo = URI.create(conf.uri).getUserInfo();
  jedis = pool.getResource();
  if (userInfo != null && userInfo.split(":", 2).length > 0) {
    jedis.clientSetname(userInfo.split(":", 2)[0]);
  }
  jedis.ping();
}
 
Example 13
Source File: JedisServiceImpl.java    From jframe with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public Jedis getJedis() {
    try {
        JedisPool pool = _jedis.get(conf.getConf(null, "redis.host"));
        if (pool == null) return null;
        return pool.getResource();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return null;
}
 
Example 14
Source File: RedisActionHistory.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<Long> getRecentActions(String clientName, long userId,int numActions) {
	List<Long> res = new ArrayList<Long>();
	JedisPool pool = poolManager.get(clientName);
	if (pool != null)
	{
		Jedis jedis = null;
		try
		{
			jedis = pool.getResource();
			String key = MemCacheKeys.getActionHistory(clientName, userId);
			Set<String> itemSet = jedis.zrange(key, 0, -1);
			for (String item : itemSet)
			{
				item = item.replaceAll("\"", "");
				res.add(0,Long.parseLong(item));// reverse order so last ones are earliest in time
			}
			if (res.size() > numActions)
				res = res.subList(0, numActions);
		}
		finally
		{
		 if (jedis != null) {
			    jedis.close();
			  }
		}
	}
	else
	{
		logger.error("No redis pool found for "+clientName);
	}
	if (logger.isDebugEnabled())
		logger.debug("For user "+userId+" found "+res.size()+" actions:"+res.toString());
	return res;
}
 
Example 15
Source File: DefaultCacheManager.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
public   static  void  main(String[] args){

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        System.err.println("oooooooooooo");
        jedisPoolConfig.setMaxTotal(10);
        jedisPoolConfig.setMaxIdle(10);
        System.err.println("11111111");
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,
                "localhost",
          6379,
        2000,
                null
        );

        jedisPool.getResource();

    }
 
Example 16
Source File: TracingJedisPoolTest.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testPoolReturnsTracedJedis() {
  JedisPool pool = new TracingJedisPool(new TracingConfiguration.Builder(mockTracer).build());

  Jedis jedis = pool.getResource();
  assertEquals("OK", jedis.set("key", "value"));
  assertEquals("value", jedis.get("key"));

  jedis.close();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example 17
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void deferExpired() {
       for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
           JedisPool jedisPool = entry.getValue();
           boolean isBroken = false;
           try {
               Jedis jedis = jedisPool.getResource();
               try {
                   for (URL url : new HashSet<URL>(getRegistered())) {
                       if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                           String key = toCategoryPath(url);
                           if (jedis.hset(key, url.toFullString(), String.valueOf(System.currentTimeMillis() + expirePeriod)) == 1) {
                               jedis.publish(key, Constants.REGISTER);
                           }
                       }
                   }
                   if (admin) {
                       clean(jedis);
                   }
                   if (!replicate) {
                       break;//  如果服务器端已同步数据,只需写入单台机器
                   }
               } catch (JedisConnectionException e){
                   isBroken = true;
               } finally {
                   if(isBroken){
                       jedisPool.returnBrokenResource(jedis);
                   } else {
                       jedisPool.returnResource(jedis);
                   }
               }
           } catch (Throwable t) {
               logger.warn("Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t);
           }
       }
   }
 
Example 18
Source File: RedisService.java    From pybbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 带有过期时间的保存数据到redis,到期自动删除
 *
 * @param key
 * @param value
 * @param expireTime 单位 秒
 */
public void setString(String key, String value, int expireTime) {
    JedisPool instance = this.instance();
    if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value) || instance == null) return;
    Jedis jedis = instance.getResource();
    SetParams params = new SetParams();
    params.px(expireTime * 1000);
    jedis.set(key, value, params);
    jedis.close();
}
 
Example 19
Source File: RedisRegistry.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
private void deferExpired() {
    for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
        JedisPool jedisPool = entry.getValue();
        boolean isBroken = false;
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                for (URL url : new HashSet<URL>(getRegistered())) {
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        String key = toCategoryPath(url);
                        if (jedis.hset(key, url.toFullString(), String.valueOf(System.currentTimeMillis() + expirePeriod)) == 1) {
                            jedis.publish(key, Constants.REGISTER);
                        }
                    }
                }
                if (admin) {
                    clean(jedis);
                }
                if (!replicate) {
                    break;//  如果服务器端已同步数据,只需写入单台机器
                }
            } catch (JedisConnectionException e){
                isBroken = true;
            } finally {
                if(isBroken){
                    jedisPool.returnBrokenResource(jedis);
                } else {
                    jedisPool.returnResource(jedis);
                }
            }
        } catch (Throwable t) {
            logger.warn("Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t);
        }
    }
}
 
Example 20
Source File: BaseCache.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
protected static Jedis getJedis(){
    JedisPool jedisPool = (JedisPool) ApplicationContextFactory.getBean("jedisPool");
    return jedisPool.getResource();
}