-
Notifications
You must be signed in to change notification settings - Fork 0
/
RedisUtils.java
78 lines (65 loc) · 2.6 KB
/
RedisUtils.java
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
package com.hp.gmall.realtime.utils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;
import java.io.*;
import java.util.Enumeration;
import java.util.Properties;
public class RedisUtils implements Closeable {
public final static String REDIS_CONFIG_PATH = "conf/redis.properties";
private JedisPool pool;
public RedisUtils(String confPath) {
this.init(confPath);
}
public static RedisUtils create() {
return new RedisUtils(REDIS_CONFIG_PATH);
}
public static RedisUtils create(String confPath) {
return new RedisUtils(confPath);
}
public Jedis getJedis() {
return this.pool.getResource();
}
public RedisUtils init(String confPath){
final JedisPoolConfig config = new JedisPoolConfig();
Properties prop = null;
InputStream inputStream = null;
try {
prop = new Properties();
inputStream = this.getClass().getClassLoader().getResourceAsStream(confPath);
prop.load(inputStream);
String host = prop.getProperty("host", Protocol.DEFAULT_HOST);
int port = Integer.parseInt(prop.getProperty("port", String.valueOf(Protocol.DEFAULT_PORT)));
int connectionTimeout = Integer.parseInt(prop.getProperty("connectionTimeout", String.valueOf(Protocol.DEFAULT_TIMEOUT)));
int soTimeout = Integer.parseInt(prop.getProperty("soTimeout", String.valueOf(Protocol.DEFAULT_TIMEOUT)));
String password = prop.getProperty("password", null);
int database = Integer.parseInt(prop.getProperty("database", String.valueOf(Protocol.DEFAULT_DATABASE)));
String clientName = prop.getProperty("clientName", this.getClass().getName());
boolean ssl = Boolean.parseBoolean(prop.getProperty("ssl", "false"));
this.pool = new JedisPool(config, host, port, connectionTimeout, soTimeout, password, database, clientName, ssl, null, null, null
);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream !=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return this;
}
public void close() {
if (null != pool) {
try {
pool.close();
} catch (Exception e) {
// 静默关闭
e.printStackTrace();
}
}
}
}