maven依赖关系:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.0</version> </dependency>
源码:
1 package StudyPro.service; 2 3 import redis.clients.jedis.Jedis; 4 import redis.clients.jedis.JedisPool; 5 import redis.clients.jedis.JedisPoolConfig; 6 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.util.Properties; 10 11 /** 12 * 使用连接池封装Redis连接工具类 13 */ 14 public class RedisUtils { 15 private static JedisPool jedisPool; 16 private static Properties properties; 17 private static String proPath = "redisConfig.properties"; 18 private static boolean authFlag; 19 private static String password; 20 21 static { 22 //读取配置文件 23 try { 24 readConfigFile(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 29 // 配置连接池 30 JedisPoolConfig poolConfig = new JedisPoolConfig(); 31 poolConfig.setMaxIdle(20); 32 poolConfig.setMinIdle(10); 33 poolConfig.setMaxTotal(30); 34 poolConfig.setMaxWaitMillis(3000); 35 poolConfig.setTestOnBorrow(true); 36 poolConfig.setTestOnReturn(true); 37 jedisPool = new JedisPool(properties.getProperty("redis.host"), Integer.valueOf(properties.getProperty("redis.port"))); 38 39 //判断是否需要密码验证 40 if ("1".equals(properties.getProperty("redis.authFlag"))) { 41 authFlag = true; 42 password = properties.getProperty("redis.password"); 43 if (password == null) { 44 try { 45 throw new Exception("redis密码没有读取到!"); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 } 50 } 51 } 52 53 private static Properties readConfigFile() throws IOException { 54 InputStream in = RedisUtils.class.getClass().getResourceAsStream("/" + proPath); 55 if (in == null) { 56 throw new IOException("读取不到配置文件:" + proPath); 57 } 58 properties = new Properties(); 59 properties.load(in); 60 in.close(); 61 return properties; 62 } 63 64 public static Jedis getResource() { 65 Jedis jedis = jedisPool.getResource(); 66 if (authFlag) { 67 jedis.auth(password); 68 } 69 return jedis; 70 } 71 72 public static void close() { 73 jedisPool.close(); 74 } 75 }
配置文件redisConfig.properties:
redis.host=10.15.1.19
redis.port=16379
# auth:0不需要密码;1需要密码
redis.authFlag=1
redis.password=wC3Xo8E5mlmgMb
测试代码:
1 package StudyPro.service; 2 3 import org.junit.Test; 4 import redis.clients.jedis.Jedis; 5 6 public class TestRedisUtils { 7 @Test 8 public void test() { 9 Jedis jedis = RedisUtils.getResource(); 10 // jedis.auth("wC3Xo8E5mlmgMb"); 11 System.out.println(jedis.get("a")); 12 jedis.close(); 13 RedisUtils.close(); 14 15 } 16 }