redis.clients.jedis.JedisPool Java Examples

The following examples show how to use redis.clients.jedis.JedisPool. 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: KeyRotationExampleIT.java    From fernet-java8 with Apache License 2.0 7 votes vote down vote up
@Before
public void setUp() throws IOException {
    initMocks(this);
    final SecureRandom random = new SecureRandom();
    redisServer = new RedisServer();
    redisServer.start();

    pool = new JedisPool();
    repository = new RedisKeyRepository(pool);
    manager = new RedisKeyManager(random, pool, repository);
    manager.setMaxActiveKeys(3);

    clearData();
    manager.initialiseNewRepository();

    resource = new ProtectedResource(repository, random);
}
 
Example #2
Source File: AppServletContextListener.java    From java-docs-samples with Apache License 2.0 7 votes vote down vote up
private JedisPool createJedisPool() throws IOException {
  String host;
  Integer port;
  config.load(
      Thread.currentThread()
          .getContextClassLoader()
          .getResourceAsStream("application.properties"));
  host = config.getProperty("redis.host");
  port = Integer.valueOf(config.getProperty("redis.port", "6379"));

  JedisPoolConfig poolConfig = new JedisPoolConfig();
  // Default : 8, consider how many concurrent connections into Redis you will need under load
  poolConfig.setMaxTotal(128);

  return new JedisPool(poolConfig, host, port);
}
 
Example #3
Source File: JedisTest.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Test
public void testJedisPool() {
	JedisPool pool = new JedisPool(config, host);
	Jedis jedis = pool.getResource();
	byte[] key = "hello ".getBytes();
	byte[] value = "world".getBytes();
	long startM = 0l, endM = 0l;
	
	startM = System.currentTimeMillis();
	for ( int i=0; i<max; i++ ) {
		key[key.length-1] = (byte)(i&0xFF);
		jedis.set(key, value);
		jedis.del(key);
	}
	endM = System.currentTimeMillis();
	System.out.println("Original Jedis loop " + max + " perform: " + (endM-startM));
}
 
Example #4
Source File: RedisPoolManager.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
private void add(String client,String host,int maxTotal,int maxIdle)
{
	logger.info("Adding Redis pool for "+client+" at "+host+" maxTotal "+maxTotal+" maxIdle "+maxIdle);
	JedisPoolConfig poolConfig = new JedisPoolConfig();
	poolConfig.setMaxTotal(maxTotal); // maximum active connections
	poolConfig.setMaxIdle(maxIdle);  // maximum idle connections

	JedisPool pool = new JedisPool(poolConfig, host);
	JedisPool existing = pools.get(client);
	pools.put(client, pool);
	if (existing != null)
	{
		logger.warn("Attempting to close previous pool for "+client);
		existing.destroy();
	}
}
 
Example #5
Source File: JedisConnectionPool.java    From slime with MIT License 6 votes vote down vote up
/**
 * @param host
 *            redis.server.ip
 * @param port
 *            redis.server.port
 */
public JedisConnectionPool(String h, int p) throws Exception {
	if (jedisPoolA == null) {
		host = h;
		port = p;
		try {
			JedisPool pool = initJedisPool(host, port);
			if (pool != null) {
				jedisPoolA = pool;
			} else {
				throw new Exception("Redis Connection Error - " + h + ":" + p);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example #6
Source File: SlackTestConfig.java    From java-slack-sdk with MIT License 6 votes vote down vote up
private SlackTestConfig(SlackConfig config) {
    this.config = config;
    CONFIG.getHttpClientResponseHandlers().add(new HttpResponseListener() {
        @Override
        public void accept(State state) {
            String json = GsonFactory.createSnakeCase(CONFIG).toJson(getMetricsDatastore().getAllStats());
            log.debug("--- (MethodsStats) ---\n" + json);
        }
    });

    // Testing with Redis
    String redisEnabled = System.getenv(Constants.SLACK_SDK_TEST_REDIS_ENABLED);
    if (redisEnabled != null && redisEnabled.equals("1")) {
        // brew install redis
        // redis-server /usr/local/etc/redis.conf --loglevel verbose
        JedisPool jedis = new JedisPool("localhost");
        CONFIG.getMethodsConfig().setMetricsDatastore(new RedisMetricsDatastore("test", jedis));
    }
}
 
Example #7
Source File: JedisPoolTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void nonDefaultDatabase() {
  JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000,
      "foobared");
  Jedis jedis0 = pool0.getResource();
  jedis0.set("foo", "bar");
  assertEquals("bar", jedis0.get("foo"));
  jedis0.close();
  pool0.destroy();
  assertTrue(pool0.isClosed());

  JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000,
      "foobared", 1);
  Jedis jedis1 = pool1.getResource();
  assertNull(jedis1.get("foo"));
  jedis1.close();
  pool1.destroy();
  assertTrue(pool1.isClosed());
}
 
Example #8
Source File: RedisComponent.java    From litchi with Apache License 2.0 6 votes vote down vote up
private Jedis getJedis(String redisKey) {
    try {
    	JedisPoolPack jedisPoolPack = jedisPoolMap.get(redisKey);
        JedisPool jedisPool = jedisPoolPack.getJedisPool();
        if (jedisPool == null) {
            LOGGER.error("jedis pool not found. key={} existKeys={}", redisKey, jedisPoolMap.keySet());
            return null;
        }
        Jedis jedis = jedisPool.getResource();
        jedis.select(jedisPoolPack.getDbIndex());
        return jedis;
    } catch (Exception e) {
        LOGGER.error("", e);
    }
    return null;
}
 
Example #9
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 #10
Source File: JedisPoolTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void getNumActiveReturnsTheCorrectNumber() {
  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"));

  assertEquals(1, pool.getNumActive());

  Jedis jedis2 = pool.getResource();
  jedis.auth("foobared");
  jedis.set("foo", "bar");

  assertEquals(2, pool.getNumActive());

  jedis.close();
  assertEquals(1, pool.getNumActive());

  jedis2.close();

  assertEquals(0, pool.getNumActive());

  pool.destroy();
}
 
Example #11
Source File: RedisHelper.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
public static byte[] getKeyValue(JedisPool jedisPool, final byte[] key) {
    return execute(jedisPool, new JedisCallback<byte[]>() {
        @Override
        public byte[] doInJedis(Jedis jedis) {
            Map<byte[], byte[]> fieldValueMap = jedis.hgetAll(key);

            List<Map.Entry<byte[], byte[]>> entries = new ArrayList<Map.Entry<byte[], byte[]>>(fieldValueMap.entrySet());
            Collections.sort(entries, new Comparator<Map.Entry<byte[], byte[]>>() {
                @Override
                public int compare(Map.Entry<byte[], byte[]> entry1, Map.Entry<byte[], byte[]> entry2) {
                    return (int) (ByteUtils.bytesToLong(entry1.getKey()) - ByteUtils.bytesToLong(entry2.getKey()));
                }
            });


            byte[] content = entries.get(entries.size() - 1).getValue();

            return content;
        }
    });
}
 
Example #12
Source File: AccessSpeedLimitTest.java    From Distributed-Kit with Apache License 2.0 6 votes vote down vote up
@Test
public void test2() throws InterruptedException {
    JedisPool jp=new JedisPool("127.0.0.1",6379);
    final RedisDistributedLockTemplate template=new RedisDistributedLockTemplate(jp);
    LimitRule limitRule=new LimitRule();
    limitRule.setSeconds(1);
    limitRule.setLimitCount(5);
    limitRule.setLockCount(7);
    limitRule.setLockTime(2);
    AccessSpeedLimit accessSpeedLimit=new AccessSpeedLimit(jp);
    SimpleDateFormat sdf=new SimpleDateFormat(" mm:ss");
    while(true){
        //10.0.0.1这个ip每1秒钟最多访问5次if块内代码.1秒超过10次后,锁定2秒,2秒内无法访问.
        if(accessSpeedLimit.tryAccess("10.0.0.1",limitRule)){
            System.out.println("yes"+sdf.format(new Date()));
        }else{
            System.out.println("no"+sdf.format(new Date()));
        }
        Thread.sleep(100);
    }
}
 
Example #13
Source File: JedisHealthStats.java    From pepper-metrics with Apache License 2.0 6 votes vote down vote up
public void collectStats() {
    if (pool instanceof PjedisPool) {
        try (Jedis jedis = ((PjedisPool)pool).getResource()) {
            constantsCollect("Host", jedis.getClient().getHost());
            constantsCollect("Port", jedis.getClient().getPort() + "");
        }
    }

    if (pool instanceof JedisPool) {
        try (Jedis jedis = ((JedisPool)pool).getResource()) {
            constantsCollect("Host", jedis.getClient().getHost());
            constantsCollect("Port", jedis.getClient().getPort() + "");
        }
    }
    gaugeCollect("NumActive", pool.getNumActive());
    gaugeCollect("NumIdle", pool.getNumIdle());
    gaugeCollect("NumWaiters", pool.getNumWaiters());
    gaugeCollect("MaxBorrowWaitTimeMillis", pool.getMaxBorrowWaitTimeMillis());
    gaugeCollect("MeanBorrowWaitTimeMillis", pool.getMeanBorrowWaitTimeMillis());
    infoCollect();
}
 
Example #14
Source File: RedisQueueObserverTest.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void run() {
    JedisPool pool = Application.getCommonCache().getJedisPool();

    try (Jedis jedis = pool.getResource()) {
        if (useTopic) {
            jedis.subscribe(new TopicProducer(), RedisQueueObserver.QUEUE_NAME);
            System.out.println("subscribe ...");
        }
        else {
            while (true) {
                // BLOCK ...
                List<String> datas = jedis.blpop(0, RedisQueueObserver.QUEUE_NAME);
                System.out.println("Reviced queue data : " + datas);
            }
        }

    }
}
 
Example #15
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 #16
Source File: RedisActionHistory.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public void addFullAction(String clientName, Action a) throws APIException {

	JedisPool pool = poolManager.get(clientName);
	if (pool != null)
	{
		Jedis jedis = null;
		try 
		{
			ActionLogEntry al = new ActionLogEntry(clientName,a);
			String val = mapper.writeValueAsString(al);
			String key = MemCacheKeys.getActionFullHistory(clientName, a.getUserId());
			jedis = pool.getResource();
			jedis.zadd(key, a.getDate().getTime()/1000, val);
			//zremrangebyscore needed
		}
		catch (JsonProcessingException e) 
		{
			logger.error("Failed to convert action to json ",e);
		}
		finally
		{
			if (jedis != null)
			{
				jedis.close();
			}
		}
	}
	else
	{
		logger.error("No redis pool found for "+clientName);
	}
}
 
Example #17
Source File: RedisMS.java    From BigData with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 为Redis数据库中的商品赋值
 * 
 * @param arr
 *            String 抢购商品数组
 * @param num
 *            int 商品库存
 */
private static void assignment(String[] arr, int num, JedisPool jedisPool) {

	// 获得连接
	Jedis jedis = jedisPool.getResource();
	boolean flag = false;

	for (int i = 0; i < arr.length; i++) {
		jedis.set(arr[i], num + "");
	}

}
 
Example #18
Source File: JedisSpringConfig.java    From belling-redis-id-generator with Apache License 2.0 5 votes vote down vote up
/**
 * @Description 
 * 
 * @author butterfly
 * @param pool
 * @return
 */
@Bean
@ConditionalOnMissingBean(JedisClient.class) // 容器中如果没有RedisClient这个类,那么自动配置这个RedisClient
public JedisClient redisClient(@Qualifier("jedisPool") JedisPool pool) {
	JedisClient jedisClient = new JedisClient();
	jedisClient.setJedisPool(pool);
	return jedisClient;
}
 
Example #19
Source File: RedisService.java    From pybbs with GNU Affero General Public License v3.0 5 votes vote down vote up
public void delString(String key) {
  JedisPool instance = this.instance();
  if (StringUtils.isEmpty(key) || instance == null) return;
  Jedis jedis = instance.getResource();
  jedis.del(key); // 返回值成功是 1
  jedis.close();
}
 
Example #20
Source File: RedisUtil.java    From zhcc-server with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化Redis连接池
 */
private static void initialPool() {
	try {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(MAX_ACTIVE);
		config.setMaxIdle(MAX_IDLE);
		config.setMaxWaitMillis(MAX_WAIT);
		config.setTestOnBorrow(TEST_ON_BORROW);
		jedisPool = new JedisPool(config, IP, PORT, TIMEOUT);
	} catch (Exception e) {
		LOGGER.error("First create JedisPool error : " + e);
	}
}
 
Example #21
Source File: RedisJedisManager.java    From calcite with Apache License 2.0 5 votes vote down vote up
private JedisPool createConsumer() {
  String pwd = password;
  if (StringUtils.isEmpty(pwd)) {
    pwd = null;
  }
  return new JedisPool(jedisPoolConfig, host, port, timeout, pwd, database);
}
 
Example #22
Source File: JedisHelper.java    From netty.book.kor with MIT License 5 votes vote down vote up
/**
 * 제디스 연결풀 생성을 위한 도우미 클래스 내부 생성자. 싱글톤 패턴이므로 외부에서 호출할 수 없다.
 */
private JedisHelper() {
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setMaxTotal(20);
    config.setBlockWhenExhausted(true);

    this.pool = new JedisPool(config, REDIS_HOST, REDIS_PORT);
}
 
Example #23
Source File: RedisPool.java    From seconds-kill with MIT License 5 votes vote down vote up
private static void initPool() {
    JedisPoolConfig config = new JedisPoolConfig();

    config.setMaxTotal(maxTotal);
    config.setMaxIdle(maxIdle);
    config.setTestOnBorrow(testOnBorrow);
    config.setBlockWhenExhausted(true);
    config.setMaxWaitMillis(maxWait);

    pool = new JedisPool(config, redisIP, redisPort, 1000 * 2);
}
 
Example #24
Source File: JedisUtil.java    From scaffold-cloud with MIT License 5 votes vote down vote up
public static JedisPool getInstance() {
    if (jedisPool == null) {
        synchronized (JedisUtil.class) {
            if (jedisPool == null) {
                jedisPool = SpringContextHolder.getBean("jedisPool");
            }
        }
    }
    return jedisPool;
}
 
Example #25
Source File: JedisPoolTest.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
@Test
public void returnResourceShouldResetState() {
  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");
    Transaction t = jedis.multi();
    t.set("hello", "world");
  } finally {
    jedis.close();
  }

  Jedis jedis2 = pool.getResource();
  try {
    assertTrue(jedis == jedis2);
    assertEquals("jedis", jedis2.get("hello"));
  } finally {
    jedis2.close();
  }

  pool.destroy();
  assertTrue(pool.isClosed());
}
 
Example #26
Source File: RedisActionHistoryTest.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Before
public void createMocks()
{
	this.mockRedisPoolManager = createMock(RedisPoolManager.class);
	this.mockJedisPool = createMock(JedisPool.class);
	this.mockJedis = createMock(Jedis.class);
}
 
Example #27
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 #28
Source File: JedisPoolTest.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
@Test
public void startWithUrl() throws URISyntaxException {
  Jedis j = new Jedis("localhost", 6380);
  j.auth("foobared");
  j.select(2);
  j.set("foo", "bar");
  JedisPool pool = new JedisPool(new URI("redis://:foobared@localhost:6380/2"));
  Jedis jedis = pool.getResource();
  assertEquals("PONG", jedis.ping());
  assertEquals("bar", jedis.get("foo"));
}
 
Example #29
Source File: RedisPoolFactory.java    From SecKillShop with MIT License 5 votes vote down vote up
@Bean
public JedisPool jedisPoolFactory() {
    JedisPoolConfig jsc = new JedisPoolConfig();
    jsc.setMaxIdle(redisConfig.getPoolMaxIdle());
    jsc.setMaxTotal(redisConfig.getPoolMaxTotal());
    jsc.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);

    JedisPool jp = new JedisPool(jsc, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getTimeout(), redisConfig.getPassword());
    return jp;
}
 
Example #30
Source File: RedisClient.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
public synchronized boolean init() {
	if (isInited)
		return Boolean.TRUE;
	try {
		String host = RedisProperties.host;
		String port = RedisProperties.port;
		String password = RedisProperties.password;
		String maxActive = RedisProperties.maxActive;
		String maxIdle = RedisProperties.maxIdle;
		String minIdle = RedisProperties.minIdle;
		String maxWait = RedisProperties.maxWait;
		String minEvictableIdleTimeMillis = RedisProperties.minEvictableIdleTimeMillis;
		String timeBetweenEvictionRunsMillis = RedisProperties.timeBetweenEvictionRunsMillis;
		poolConfig.setMaxTotal(Integer.parseInt(StringUtils.isBlank(maxActive) ? "1000" : maxActive.trim()));
		poolConfig.setMaxIdle(Integer.parseInt(StringUtils.isBlank(maxIdle) ? "1000" : maxIdle.trim()));
		poolConfig.setMinIdle(Integer.parseInt(StringUtils.isBlank(minIdle) ? "10" : minIdle.trim()));
		poolConfig.setMaxWaitMillis(Long.parseLong(StringUtils.isBlank(maxWait) ? "20000" : maxWait.trim()));
		if (StringUtils.isNotBlank(minEvictableIdleTimeMillis)) // 设定多长时间视为失效链接
			poolConfig.setMinEvictableIdleTimeMillis(Integer.parseInt(minEvictableIdleTimeMillis.trim()));
		if (StringUtils.isNotBlank(timeBetweenEvictionRunsMillis)) // 设定每隔多长时间进行有效检查与上面参数同时使用
			poolConfig.setTimeBetweenEvictionRunsMillis(Integer.parseInt(timeBetweenEvictionRunsMillis.trim()));
		jedisPool = new JedisPool(poolConfig, host, Integer.parseInt(port.trim()), timeout, password);

		isInited = Boolean.TRUE;
		return Boolean.TRUE;
	} catch (Exception e) {
		logger.error(" Initialization Redis Exception :", e);
	}
	return Boolean.FALSE;

}