Jedis使用连接池(Java)

package com.djhu.redis.test;

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

public class JedisFactory
{
	// 最大可用连接数,默认值为8,如果赋值为-1则表示不限制
	private static int MAX_TOTAL = 256;
	// 最大空闲连接数,默认值为8
	private static int MAX_IDLE = 32;
	// 最小空闲连接数
	private static int MIN_IDLE = 4;
	// 最大等待连接毫秒数,默认值为-1表示永不超时
	private static int MAX_WAIT = 3000;
	// 连接redis超时时间
	private static int TIMEOUT = 3000;
	// true表示验证连接
	private static boolean TEST_ON_BORROW = true;

	//连接池
	private static JedisPool jedisPool = null;
	public static void initJedisPool(String IP, int port, String password)
	{
		try
		{
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(MAX_TOTAL);
			config.setMaxIdle(MAX_IDLE);
			config.setMinIdle(MIN_IDLE);
			config.setMaxWaitMillis(MAX_WAIT);
			config.setTestOnBorrow(TEST_ON_BORROW);
			
			jedisPool = new JedisPool(config, IP, port, TIMEOUT, password);
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public synchronized static Jedis getConnection()
	{
		try
		{
			if (jedisPool != null)
			{
				Jedis resource = jedisPool.getResource();
				return resource;
			} else
			{
				return null;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public static void returnResource(final Jedis jedis)
	{
		if (jedis != null)
		{
			jedis.close();
		}
	}
	
	public static void main(String[] args)
	{
		initJedisPool("localhost",6379,null);
		Jedis redis = getConnection();
		redis.select(1);
		//redis.set("key01", "a");
		//redis.set("key02", "b");
		//redis.set("key03", "c");
		System.out.print(redis.dbSize());
		
		returnResource(redis);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*