Redis连接池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.alwyn.redis.test;

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

public class RedisPoolUtils {
private static volatile JedisPool jedisPool = null;
//被volatile修饰的变量不会被本地线程缓存,对该变量的读写都是直接操作共享内存,保证变量值的“可见性”

//不能在外部创建对象
private RedisPoolUtils() {
}

public static JedisPool getInstance() { //双锁校验机制
if (jedisPool == null) {
synchronized (RedisPoolUtils.class) {
if (jedisPool == null) {
JedisPoolConfig poolConfig = new JedisPoolConfig();

//设置Jedis最大连接数
poolConfig.setMaxTotal(100);

///设置Jedis连接最大空闲数
poolConfig.setMaxIdle(10);

//设置获取Jedis连接的最大等待时间(50秒)
poolConfig.setMaxWaitMillis(50 * 1000);

//设置在获取Jedis连接时,自动检验连接是否可用
poolConfig.setTestOnBorrow(true);

//设置在将连接放回池中前,自动检验连接是否有效
poolConfig.setTestOnReturn(true);

//设置自动测试池中的空闲连接是否都是可用连接
poolConfig.setTestWhileIdle(true);

jedisPool = new JedisPool(poolConfig,"39.107.226.243", 6379);
}
}
}
return jedisPool;
}

/**
* 关闭Jedis连接
* @param jedisPool
* @param jedis
*/
public static void release(JedisPool jedisPool, Jedis jedis) {
if (null != jedis) {
jedisPool.returnResourceObject(jedis);
}
}

}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.alwyn.redis.test;

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

public class JedisPoolDemo {
public static void main(String[] args) {
JedisPool jedisPool = RedisPoolUtils.getInstance();
Jedis jedis = null;
try
{
jedis = jedisPool.getResource();
jedis.set("k18","v183");
} catch (Exception e) {
e.printStackTrace();
}finally{
RedisPoolUtils.release(jedisPool, jedis);
}
}
}

0%