java操作redis redis连接池

redis 作为缓存型数据库,越来越受到大家的欢迎,这里简单介绍一下 java 如何操作 redis。


1、java 连接 redis

java 通过需要jedis 的 jar 包获取 Jedis 连接。   

jedis-2.8.0.jar

public void getConn()
{
	// 获取 jedis 连接
	Jedis jedis = new Jedis("127.0.0.1",6379);
	// 获取 redis 中以 FIELD 开头的 key
	Set<String> keys = jedis.keys("FIELD*");
	for(String key : keys)
	{System.out.println(key);
	}
}

2、java 获取 jedis 连接池

如果每次连接 redis 都 new1 个 Jedis 的话,势必耗费很多资源,这里就提到 redis 连接池。

所需 jar 包

commons-pool2-2.3.jar

jedis-2.8.0.jar

public class RedisUtil 
{
	private static JedisPool pool = null;
/**
 * 获取jedis连接池
 * */
public static JedisPool getPool()
{
	if(pool == null)
	{
		//创建jedis连接池配置
		JedisPoolConfig config = new JedisPoolConfig();
		//最大连接数
		config.setMaxTotal(100);
		//最大空闲连接
		config.setMaxIdle(5);
		//创建redis连接池
		pool = new JedisPool(config,"127.0.0.1",6379,超时时长);
	}
	return pool;
}

/**
 * 获取jedis连接
 * */
public static Jedis getConn()
{
	return getPool().getResource();
}

}


新版本 jedis 的 jar 包获取连接池,使用完后用 jedis.close() 归还连接:

@Test
	public void testPool()
	{
		// 获取 jedis 连接
		Jedis jedis = RedisUtil.getConn();	
		String value = jedis.get(key);
		// 使用之后记得关闭连接
		jedis.close();}

老版本的 jedis jar 获取连接,使用完要用 pool.returnResource(jedis); 归还连接

public void testPool()
{
	// 获取 jedis 连接
	JedisPool pool = RedisUtil.getPool();
	Jedis jedis = pool.getResource();
	String value = jedis.get(key);
	// 使用之后记得关闭连接
	pool.returnResource(jedis);
}