java 集成 redis以及redis线程池

java 集成 redis以及redis线程池

  • redis远程连接需要用到jedis-x.jar、jedis线程池需要引入commons-pool2.x.jar、slf4j-api-x.jar包

1、redis线程池

public class RedisPool {
	static String redisURL;
	static Integer redisPORT;
	static String redisPASS;
	private static JedisPool jedisPool = null;
	
	private RedisPool() {}
	
	public static JedisPool getJedisPoolInstance() {
        if (jedisPool == null) {
            synchronized (RedisPool.class) {
                if (jedisPool == null) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(10);           // 最大连接数
                    poolConfig.setMaxIdle(2);              // 最大空闲连接数
                    poolConfig.setMaxWaitMillis(1000 * 10);  // 最大等待时间(毫秒)
                    poolConfig.setTestOnReturn(false);
                    poolConfig.setTestOnBorrow(true);       // 检查连接可用性, 确保获取的redis实例可用
                    poolConfig.setTestOnCreate(false);
                    
                    jedisPool = new JedisPool(poolConfig, redisURL, redisPORT,3000,redisPASS);
                }
            }
        }
        
        return jedisPool;
    }
	
	/**
     * 从连接池中获取一个 Jedis 实例(连接)
     * @return Jedis 实例
     */
    public static Jedis getJedisInstance() {
        
        return getJedisPoolInstance().getResource();
    }
    
    /**
     * 将Jedis对象(连接)归还连接池
     * @param jedis 连接对象
     */
    public static void release(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}

2、Redis工具类

public class RedisUtils {
	private Jedis jedis;
	
	public RedisUtils(Jedis jedis) {
		this.jedis = jedis;
	}
	
	public void set(String key, String value) {
		jedis.set(key, value);
	}
	
	public void set(String key, String value,int seconds) {
		set(key,value);
		jedis.expire(key, seconds);
	}
	
	public String get(String key) {
		return jedis.get(key);
	}
	
	public boolean hasKey(String key) {
		return jedis.exists(key);
	}
	
	public Long del(String key) {
		return jedis.del(key);
	}
	
}

3、redis测试(多线程)

public class main {


	public static void main(String[] args){
		for(int i = 0; i<100; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					Jedis jedis = RedisPool.getJedisInstance();
					RedisUtils redisUtils = new RedisUtils(jedis);
					redisUtils.set(Thread.currentThread().getName(), "RedisSuccess",10);
					RedisPool.release(jedis);
				}
			}).start();
		}
	}
}

你可能感兴趣的:(java,redis)