二、redis.propertiesredis.clients jedis 3.7.0 org.slf4j slf4j-api 1.8.0-beta0 org.slf4j slf4j-simple 1.8.0-beta0
#redis服务器ip redis_host=192.168.xxx.xxx #redis服务端口 redis_port=6379 #redis验证密码(如果有) redis_password=xxxx #redis操作超时 redis_timeout=10000 #redis所选库 redis_db=1 #redis最大等待连接中的数量 redis_maxidle=10 #redis最小等待连接中的数量 redis_minidle=2 #redis最大数据库连接数 redis_maxtotal=20三、redisUtil.java
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class redisUtil{
//如果配置文件里有,则使用配置文件中的,若无,则使用这里的
private static JedisPool pool = null;
private static String ip = "localhost";
private static int port = 6379;
private static String auth = "";
//配置文件地址
private static File getPath() {
return new File("src/main/resources/redis.properties");
}
//初始化连接池
private static JedisPoolConfig initConfig() {
JedisPoolConfig config = new JedisPoolConfig();
Properties p = new Properties();
try {
File path = getPath();
if (!path.exists()) {
System.err.println("configuration file not found Exception : redis.properties");
return config;
}
//读取配置文件
p.load(new FileReader(path));
//设置连接池,配置文件设置为默认值
ip = p.getProperty("jedis.datasource.ip", ip);
port = Integer.parseInt(p.getProperty("jedis.datasource.port", String.valueOf(port)));
auth = p.getProperty("jedis.datasource.auth", auth);
if (p.containsKey("jedis.pool.maxActive")) {
config.setMaxTotal(Integer.parseInt(p.getProperty("jedis.pool.maxActive")));
}
if (p.containsKey("jedis.pool.maxIdle")) {
config.setMaxIdle(Integer.parseInt(p.getProperty("jedis.pool.maxIdle")));
}
if (p.containsKey("jedis.pool.maxWait")) {
config.setMaxWaitMillis(Integer.parseInt(p.getProperty("jedis.pool.maxWait")));
}
if (p.containsKey("jedis.pool.testOnBorrow")) {
config.setTestOnBorrow(Boolean.parseBoolean(p.getProperty("jedis.pool.testOnBorrow")));
}
if (p.containsKey("jedis.pool.testOnReturn")) {
config.setTestOnReturn(Boolean.parseBoolean(p.getProperty("jedis.pool.testOnReturn")));
}
} catch (IOException e) {
e.printStackTrace();
}
return config;
}
private static synchronized void initPool() {
if (null == pool) {
JedisPoolConfig config = initConfig();
pool = new JedisPool(config, ip, port, 5000, auth);
}
}
public static Jedis getResource() {
if (null == pool) {
initPool();
}
return pool.getResource();
}
public static void returnResource(Jedis resource) {
if (null != pool) {
pool.returnResource(resource);
} else {
resource.close();
}
}
//关闭连接,一般不关闭
public static void close() {
if (null != pool) {
pool.close();
}
}
}
四、测试工具类
RedisTest.java
public class RedisTest {
public static void main(String[] args) {
Jedis jedis = RedisUitl.getResource();
jedis.set("name1","zwh");
System.out.println(jedis.get("name1"));
//System.out.println(jedis.ttl("name1"));
Kedis.returnResource(jedis);
}
}



