JedisUtil
Jedis(Java操控Redis)
基础写法
- jar包:jedis-2.9.0.jar
- 创建Jedis对象:
Jedis jedis = new Jedis(“IP地址”,端口号); - 可以对Jedis对象进行操作(添加,查询,删除等)
例:添加:jedis.set(“key”,”value”); - 关闭:Jedis:jedis.close()
连接池
- 连接池jar包:commons-pool2-2.2.jar
- Jedis连接池的配置:
JedisPoolConfig config = new JedisPoolConfig();
配置方式例:
连接池的最大值config.setMaxTotal(100);
按照配置新建连接池:
JedisPool jedisPool = new JedisPool(config,“IP地址”,端口号); - 获取redis的资源:Jedis jedis = jedisPool.getResource();
- 关闭Jedis:jedis.close()
JedisUtil的写法
public static Jedis jedis;
public static Jedis getJedisConnection(){
if (jedis==null) {
//配置文件redis.properties内容 在 下方 另附
InputStream is=JedisPool.class.getResourceAsStream("/redis.properties");
Properties prop= new Properties();
try {
prop.load(is);
} catch (IOException e) {
e.printStackTrace();
}
String host = prop.getProperty("host");
int port = new Integer(prop.getProperty("prot"));
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(new Integer(prop.getProperty("maxTotal")));
config.setMaxIdle(new Integer(prop.getProperty("maxIdle")));
config.setMaxWaitMillis(new Integer(prop.getProperty("maxWaitMillis")));
JedisPool pool = new JedisPool(config, host, port);
return pool.getResource();
}
return jedis;
}
配置文件 redis.properties 内容
host=127.0.0.1
post=6379
maxIdle=10
maxWaitMillis=10000
maxTotal=100