java配置redis连接池

1新增依赖


  4.0.0
  com.gc
  redisDemo
  0.0.1-SNAPSHOT
  
  
    redis.clients
    jedis
    2.9.0

  

    junit
    junit
    4.12
    test

  

    org.apache.commons
    commons-pool2
    2.4.2

  
  
  

由于使用的是jedis2.9 在使用jedisPool选择的是第三个构造jedisPool的方法

public JedisPool() {
    this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
  }

  public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) {
    this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null,
        Protocol.DEFAULT_DATABASE, null);
  }

  public JedisPool(String host, int port) {
    this(new GenericObjectPoolConfig(), host, port, Protocol.DEFAULT_TIMEOUT, null,
        Protocol.DEFAULT_DATABASE, null);
  }

GenericObjectPoolConfig 中配置了默认的config信息 ,使用此方法初始化一个jedisPool连接池

package redisDemo;

import org.junit.Test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * redis连接池
 * @Description: TODO(用一句话描述该文件做什么)  
* @author gc 
* @date 2018年10月2日  
*
 */
public class RedisPool {
	public Jedis getJedis(){
		
		JedisPool jedisPool = new JedisPool("192.168.34.3",6379);
		Jedis jedis=null;
	try{
		
		jedis =jedisPool.getResource();
		jedis.auth("root");
	}catch (Exception e){
		e.printStackTrace();
	}finally {
		if(jedisPool!=null){
			jedisPool.close();
		}
	}
	return jedis;	
}
	@Test
	public  void testJedis(){
		Jedis jedis = getJedis();
		String username = jedis.get("username");
		System.out.println(username);
        jedis.close();
		
	}
	
	
	
	
}

java配置redis连接池_第1张图片

完成连接池的初步创建   在2.9版本中继承GenericObjectPoolConfig

package redis.clients.jedis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class JedisPoolConfig extends GenericObjectPoolConfig {
  public JedisPoolConfig() {
    // defaults to make your life with connection pool easier :)
    setTestWhileIdle(true);
    setMinEvictableIdleTimeMillis(60000);
    setTimeBetweenEvictionRunsMillis(30000);
    setNumTestsPerEvictionRun(-1);
  }
}

故使用默认的连接池配置

你可能感兴趣的:(redis)