java操作redis redis连接池

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c295477887/article/details/52249995

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

扫描二维码关注公众号,回复: 3818124 查看本文章

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);
}


猜你喜欢

转载自blog.csdn.net/c295477887/article/details/52249995