maven
1 <properties> 2 <jedis.version>3.0.1</jedis.version> 3 <junit.verion>4.12</junit.verion> 4 <log4j.verison>2.12.1</log4j.verison> 5 <slf4j.version>1.7.28</slf4j.version> 6 <!--<commons-pool2.version>2.6.2</commons-pool2.version>--> 7 </properties> 8 9 <dependencies> 10 <dependency> 11 <groupId>redis.clients</groupId> 12 <artifactId>jedis</artifactId> 13 <version>${jedis.version}</version> 14 </dependency> 15 16 <dependency> 17 <groupId>junit</groupId> 18 <artifactId>junit</artifactId> 19 <version>${junit.verion}</version> 20 <scope>compile</scope> 21 </dependency> 22 23 <dependency> 24 <groupId>org.apache.logging.log4j</groupId> 25 <artifactId>log4j-core</artifactId> 26 <version>${log4j.verison}</version> 27 </dependency> 28 <dependency> 29 <groupId>org.slf4j</groupId> 30 <artifactId>slf4j-api</artifactId> 31 <version>${slf4j.version}</version> 32 </dependency> 33 <dependency> 34 <groupId>org.slf4j</groupId> 35 <artifactId>slf4j-log4j12</artifactId> 36 <version>${slf4j.version}</version> 37 </dependency> 38 </dependencies>
redis.properties
1 #最大闲置数 2 redis.maxIdle=30 3 #最小闲置数 4 #redis.minIdle=10 5 #最大连接数 6 redis.maxTotal=100 7 #连接安装redis服务器的IP地址 8 redis.host=192.168.101.101 9 #redis的默认端口 10 redis.port=6379
JedisUtil
1 public class JedisUtil {
2 private static Properties properties = new Properties();
3 private static JedisPoolConfig config = new JedisPoolConfig();
4 private static JedisPool pool;
5
6 private JedisUtil() {
7
8 }
9
10 static {
11 InputStream inputStream = JedisUtil.class.getClassLoader().getResourceAsStream("redis.properties");
12 try {
13 properties.load(inputStream);
14 config.setMaxTotal(Integer.parseInt(properties.getProperty("redis.maxTotal")));
15 config.setMaxIdle(Integer.parseInt(properties.getProperty("redis.maxIdle")));
16 pool = new JedisPool(config, properties.getProperty("redis.host"), Integer.parseInt(properties.getProperty("redis.port")));
17 if (inputStream != null) {
18 inputStream.close();
19 }
20 } catch (IOException e) {
21 e.printStackTrace();
22 }
23
24 }
25
26
27 public static Jedis getResource() {
28 return pool.getResource();
29 }
30
31 public static void close(Jedis jedis) {
32 if (jedis != null) {
33 jedis.close();
34 }
35 }
36
37 public static void shutdown() {
38 if (pool != null) {
39 if (pool.getNumActive() == 0) {
40 pool.close();
41 }
42 }
43 }
44 }
Test
1 Jedis resource = JedisUtil.getResource();
2 System.out.println( resource.get("name"));
3 JedisUtil.close(resource);
4 JedisUtil.shutdown();