Fork me on GitHub

redis连接池及常用API封装

前言

之前就有文章提到了redis如何安装redis和简单使用 但是在这里就不是简单的使用了。而是封装自己的redis连接池,同时使用Jedis封装操作redis的API。

注意:以下使用的@Slf4j注解为lombok工具及其依赖。如果没有使用lombok只需要将其删掉,重新在类中定义日志即可。也可以将所有日志打印删掉。

Redis连接池

首先直接将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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

/**
* Jedis连接Redis的连接池
*
* @author : ChenCong
* @date : Created in 17:22 2018/3/2
*/
public class RedisPool {

/**
* jedis 连接池
*/
private static JedisPool pool;

/**
* 最大连接数
*/
private static Integer maxTotal = PropertiesUtil.getIntegerProperty("redis.max.total", 20);

/**
* 在jedisPool中最大idle状态(空闲)
*/
private static Integer maxIdle = PropertiesUtil.getIntegerProperty("redis.max.idle", 10);

/**
* 在jedisPool当中最小的idle状态(空闲)
*/
private static Integer minIdle = PropertiesUtil.getIntegerProperty("redis.min.idle", 2);

/**
* 在Borrow一个jedis实例的时候是否进行验证操作。
* 如果赋值为true,则拿到的jedis是可用的
*/
private static Boolean testOnBorrow = PropertiesUtil.getBooleanProperty("redis.test.borrow", true);


/**
* 在return一个jedis实例时候,是否要进行测试,
* 如果赋值为true时,则放回的jedis实例为可用的
*/
private static Boolean testOnReturn = PropertiesUtil.getBooleanProperty("redis.test.return", true);
/**
* 获取RedisIP
*/
private static String redisIp = PropertiesUtil.getProperty("redis.ip");

/**
* 获取RedisPort
*/
private static Integer redisPort = PropertiesUtil.getIntegerProperty("redis.port");

/**
* 初始化JedisPoolConfig连接池
*/
private static void initPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);

config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);

/*
* 连接耗尽时是否阻塞,false则会抛出异常,true阻塞直到超时,默认为true
*/
config.setBlockWhenExhausted(true);

pool = new JedisPool(config, redisIp, redisPort, 1000 * 2);
}

/*
* 初始化Jedis连接池
*/
static {
initPool();
}

/**
* 获取jedis连接
*
* @return jedis
*/
public static Jedis getJedis() {
return pool.getResource();
}


/**
* 放回jedis
*
* @param jedis jedis
*/
public static void returnBrokenResource(Jedis jedis) {
pool.returnBrokenResource(jedis);
}

/**
* 放回jedis
*
* @param jedis jedis
*/
public static void returnResource(Jedis jedis) {
pool.returnResource(jedis);
}

public static void main(String[] args) {
Jedis jedis = pool.getResource();
jedis.set("chencongKey","chencongValue");
returnResource(jedis);

/*获取值*/
System.out.println(jedis.get("chencongKey"));

/*
* 临时调用,销毁连接池中所有连接
*/
pool.destroy();

System.out.println("program is end");
}
}

关于PropertiesUtil这个工具类只是获取*.properties配置文件的参数的封装类而已。哦,对了,关于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
# jedis 连接redis 时的配置文件
# redis config start

# redis ip
redis.ip=127.0.0.1

# redis port
redis.port=6379
# 最大连接数
redis.max.total=20

# 最大空闲数
redis.max.idle=10

# 最小空闲数
redis.min.idle=2

# 从jedis连接池当中获取连接时,检验并返回可用的连接
redis.test.borrow=true

# 将连接放回jedis连接池时,检验并返回可用的连接
redis.test.return=false

# redis config end

关于PropertiesUtil中的方法都有重载,一:直接通过key获取参数值,二:当key对应参数值不存在时,给予默认值。

1
2
3
4
/**
* 最大连接数
*/
private static Integer maxTotal = PropertiesUtil.getIntegerProperty("redis.max.total", 20);

这个获取最大连接数的redis.max.total为key,20为默认值。如果redis.max.total对应的配置文件值不为null则返回其值,否则返回默认值20.

如果不太清楚如何获取*.properties配置文件。我还是将这个工具类放上来。

PropertiesUtil

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/**
* 读取properties配置文件的工具类<br>
* 2018年3月10日21:44:34 新增获取Boolean int类型的方法及其重载方法
*
* @author chencong
*/
public class PropertiesUtil {

/**
* 读取日志
*/
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

/**
* properties属性
*/
private static Properties props;

/*
* 静态代码块读取制定配置文件
*/
static {
/*
* 应为使用了maven环境隔离,编译之后都存在于src下面,因此这里使用指明读取的是哪一个配置文件就行了<br>
* 切记不要使用这种:src/resources.dev/data.properties 会出现异常
* 直接指明配置文件就行了
*/
String fileName = "data.properties";
props = new Properties();
try {
props.load(
new InputStreamReader(
PropertiesUtil.class
.getClassLoader().
getResourceAsStream(fileName), "UTF-8"));
} catch (IOException e) {
logger.error("配置文件读取异常", e);
}
}

/**
* 获取配置文件当中key所对应值
*
* @param key key
* @return 返回key所对应的值,存在则返回,不存在则返回null
*/
public static String getProperty(String key) {
String value = props.getProperty(key.trim());
if (StringUtils.isBlank(value)) {
return null;
}
return value.trim();
}

/**
* 获取配置文件当中key所对应的值,同时给予默认值。<br>
* 当key所对应的值不存在时,返回参数当中给予的默认值
*
* @param key key
* @param defaultValue 默认值
* @return 返回key对应值,不存在或者为null时返回默认值defaultValue
*/
public static String getProperty(String key, String defaultValue) {
String value = props.getProperty(key.trim());
if (StringUtils.isBlank(value)) {
value = defaultValue;
}
return value.trim();
}

/**
* 获取配置文件当中key所对应值,存在则进行数字转换。将其返回
*
* @param key key
* @return 返回key对应的值,不存在或发生NumberFormatException则返回null
*/
public static Integer getIntegerProperty(String key) {
String value = props.getProperty(key.trim());
Integer result;
try {
result = Integer.parseInt(value);
} catch (NumberFormatException e) {
logger.info("参数转换异常:" + e.getMessage());
return null;
}
return result;
}

/**
* 获取配置文件当中key所对应值,存在则进行数字转换。将其返回
*
* @param key key
* @param defaultValue 默认值
* @return 返回key对应的值,不存在时或发生NumberFormatException则返回defaultValue
*/
public static Integer getIntegerProperty(String key, Integer defaultValue) {
String value = props.getProperty(key);
Integer result;
if (StringUtils.isBlank(value)) {
result = defaultValue;
return result;
}
try {
result = Integer.parseInt(value);
} catch (NumberFormatException e) {
logger.info("参数转换异常:" + e.getMessage());
result = defaultValue;
}
return result;
}

/**
* 获取配置文件当中key所对应值<br>
* 如果其值为true则返回true,false或其他值则返回false,为空时返回null
*
* @param key key
* @return key对应的值,值为true时返回true,false或其他值则返回false
*/
public static Boolean getBooleanProperty(String key) {
String value = props.getProperty(key.trim()).trim();
Boolean result;
if (StringUtils.isBlank(value)) {
return null;
}
result = "true".equals(value);
return result;
}

/**
* 获取配置文件当中key所对应值<br>
* 如果其值为true则返回true,false或其他值则返回false,为null时返回defaultValue
*
* @param key key
* @param defaultValue 默认值
* @return key对应的值,值为true时返回true,false或其他值则返回false
*/
public static Boolean getBooleanProperty(String key, Boolean defaultValue) {
String value = props.getProperty(key.trim()).trim();
Boolean result;
if (StringUtils.isBlank(value)) {
result = defaultValue;
return result;
}
result = "true".equals(value);
return result;
}
}

RedisPoolUtil工具类

直接上工具类

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/**
* redisPoolUtil工具类
*
* @author chencong
*/
@Slf4j
public class RedisPoolUtil {
/**
* jedis set方法,通过设置值过期时间exTime,单位:秒<br>
* 为后期session服务器共享,Redis存储用户session所准备
*
* @param key key
* @param value value
* @param exTime 过期时间,单位:秒
* @return 执行成功则返回result 否则返回null
*/
public static String setEx(String key, String value, int exTime) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.setex(key, exTime, value);
} catch (Exception e) {
log.error("set key:{} value{} error", key, value, e);
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
}

/**
* 对key所对应的值进行重置过期时间expire
*
* @param key key
* @param exTime 过期时间 单位:秒
* @return 返回重置结果, 1:时间已经被重置,0:时间未被重置
*/
public static Long expire(String key, int exTime) {
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.expire(key, exTime);
} catch (Exception e) {
log.error("expire key:{} error ", key, e);
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;

}

/**
* jedis set方法
*
* @param key key
* @param value value
* @return 执行成功则返回result,否则返回null
*/
public static String set(String key, String value) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.set(key, value);
} catch (Exception e) {
log.error("set key:{} value{} error", key, value, e);
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
}

/**
* jedis get方法
*
* @param key key
* @return 返回key对应的value 异常则返回null
*/
public static String get(String key) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.get(key);
} catch (Exception e) {
log.error("set key:{}error", key, e);
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
}

/**
* jedis 删除方法
*
* @param key key
* @return 返回结果,异常返回null
*/
public static Long del(String key) {
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.del(key);
} catch (Exception e) {
log.error("del key:{} error", key, e);
RedisPool.returnBrokenResource(jedis);
return result;
}
return result;
}

/**
* xxxx描述信息
*
* @param args 参数
*/
public static void main(String[] args) {
Jedis jedis = RedisPool.getJedis();
RedisPoolUtil.set("keyTest", "keyValue");

String value = RedisPoolUtil.get("keyTest");

RedisPoolUtil.setEx("keyEx", "valueEx", 60 * 10);

RedisPoolUtil.expire("keyTest", 60 * 20);

}
}

redis操作当中的set get setEx del方法都已很明确。各方法的文档注释都很明了清晰。

联系

聪聪的独立博客 ,一个喜欢技术,喜欢钻研的95后。如果你看到这篇文章,千里之外,我在等你联系。

坚持原创技术分享,您的支持将鼓励我继续创作!