jedis是redis为java提供的原生API,也是是我们日常开发中常用的,个人日常用的简单总结下
maven pom.xml坐标,引入jar包
redis.clients
jedis
2.9.0
1、连接池主要参数配置redis.properties
#是否使用JedisPool默认的配置,确定true,默认true
defaultSetting=false;
#redis地址
redis.host=192.168.172.74
#redis端口号
redis.port=6379
#redis的密码
redis.auth=test
#jedisPool的timeout时间,默认2000
connectionTimeOut=2000
#最大空闲连接数,默认8个
redis.maxIdle=8
#最大连接数,默认8个
redis.maxTotal=8
#最小空闲连接数,默认0
redis.minIdle=0
#获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常,小于零:阻塞不确定的时间,默认-1
redis.maxWaitMillis=-1
#逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
redis.minEvictableIdleTimeMillis=1800000
#在获取连接的时候检查有效性,默认false
redis.testOnBorrow=false
#在空闲时检查有效性,默认false
redis.testWhileIdle=false
#逐出扫描的时间间隔(毫秒)如果为负数,则不运行逐出线程,默认-1
redus.timeBetweenEvictionRunsMillis=-1
#连接耗尽时是否阻塞,false报异常,ture阻塞直到超时,默认true
redis.blockWhenExhausted=true
#每次逐出检查时 逐出的最大数目 如果为负数就是:1/abs(n),默认3
redis.numTestsPerEvictionRun=3
#对象空闲多久后逐出,当空闲时间>该值 且 空闲连接>最大空闲数时直接逐出,不再根据MinEvictableIdleTimeMillis判断(默认逐出策略)
redis.softMinEvictableIdleTimeMillis=1800000
#设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
redis.evictionPolicyClassName=org.apache.commons.pool2.impl.DefaultEvictionPolicy
#是否启用pool的jmx管理功能,默认true
redis.jmxEnabled=true
#是否启用后进先出,默认true
redis.lifo=true
2、加载配置文件
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
public class LoadConfig {
/**
* 加载配置文件
* @param path
* @return
* @throws IOException
*/
public static Properties load(String path) throws IOException{
URL resource = LoadConfig.class.getClassLoader().getResource(path);
if (resource == null) {
throw new FileNotFoundException("没有找到指定的配置文件:" + path);
}
//加载配置文件
InputStream input = new FileInputStream(resource.getFile());
Properties p = new Properties();
p.load(input);
return p;
}
}
3、初始化连接池
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.JedisPool;
public class RedisPoolConfig {
private static final String PATH = "redis.properties";//配置路径
private static ReentrantLock lockPool = new ReentrantLock();
private static JedisPool jedisPool;
/**
* 初始化Jedis连接池
* @throws IOException
*/
public static void initialPool() throws IOException{
//加载redis配置
Properties p = LoadConfig.load(PATH);
String host = (p.getProperty("redis.host") == null || "".equals(p.getProperty("redis.host"))) ? "localhost" : p.getProperty("redis.host");
int port = (p.getProperty("redis.port") == null || "".equals(p.getProperty("redis.port"))) ? 6379 : Integer.parseInt(p.getProperty("redis.port"));
String auth = p.getProperty("redis.auth");
int poolTimeOut = (p.getProperty("connectionTimeOut") == null || "".equals(p.getProperty("connectionTimeOut"))) ? 2000 : Integer.parseInt(p.getProperty("connectionTimeOut"));
//判断使用默认的配置方式还是采用自定义配置方式,
boolean isSetDefault = (p.getProperty("defaultSetting") == null || "".equals(p.getProperty("defaultSetting"))) ? true : Boolean.parseBoolean(p.getProperty("defaultSetting"));
if (isSetDefault) {
jedisPool = new JedisPool(new GenericObjectPoolConfig(), host, port, poolTimeOut, auth);
} else {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
String blockWhenExhausted = p.getProperty("redis.blockWhenExhausted");
if (blockWhenExhausted != null) {
config.setBlockWhenExhausted(Boolean.parseBoolean(blockWhenExhausted));
}
String evictionPolicyClassName = p.getProperty("redis.evictionPolicyClassName");
if (evictionPolicyClassName != null) {
config.setEvictionPolicyClassName(evictionPolicyClassName);
}
String jmxEnabled = p.getProperty("redis.jmxEnabled");
if (jmxEnabled != null) {
config.setJmxEnabled(Boolean.parseBoolean(jmxEnabled));
}
String lifo = p.getProperty("redis.lifo");
if (lifo != null) {
config.setLifo(Boolean.parseBoolean(lifo));
}
String maxIdle = p.getProperty("redis.maxIdle");
if (maxIdle != null) {
config.setMaxIdle(Integer.parseInt(maxIdle));
}
String maxTotal = p.getProperty("redis.maxTotal");
if (maxTotal != null) {
config.setMaxTotal(Integer.parseInt(maxTotal));
}
String maxWaitMillis = p.getProperty("redis.maxWaitMillis");
if (maxWaitMillis != null) {
config.setMaxWaitMillis(Long.parseLong(maxWaitMillis));
}
String minEvictableIdleTimeMillis = p.getProperty("redis.minEvictableIdleTimeMillis");
if (minEvictableIdleTimeMillis != null) {
config.setMinEvictableIdleTimeMillis(Long.parseLong(minEvictableIdleTimeMillis));
}
String minIdle = p.getProperty("redis.minIdle");
if (minIdle != null) {
config.setMinIdle(Integer.parseInt(minIdle));
}
String numTestsPerEvictionRun = p.getProperty("redis.numTestsPerEvictionRun");
if (numTestsPerEvictionRun != null) {
config.setNumTestsPerEvictionRun(Integer.parseInt(numTestsPerEvictionRun));
}
String softMinEvictableIdleTimeMillis = p.getProperty("redis.softMinEvictableIdleTimeMillis");
if (softMinEvictableIdleTimeMillis != null) {
config.setSoftMinEvictableIdleTimeMillis(Long.parseLong(softMinEvictableIdleTimeMillis));
}
String testOnBorrow = p.getProperty("redis.testOnBorrow");
if (testOnBorrow != null) {
config.setTestOnBorrow(Boolean.parseBoolean(testOnBorrow));
}
String testWhileIdle = p.getProperty("redis.testWhileIdle");
if (testWhileIdle != null) {
config.setTestWhileIdle(Boolean.parseBoolean(testWhileIdle));
}
String timeBetweenEvictionRunsMillis = p.getProperty("redus.timeBetweenEvictionRunsMillis");
if (timeBetweenEvictionRunsMillis != null) {
config.setTimeBetweenEvictionRunsMillis(Long.parseLong(timeBetweenEvictionRunsMillis));
}
jedisPool = new JedisPool(config, host, port, poolTimeOut, auth);
}
}
/**
* 初始化连接池
* @return
* @throws IOException
*/
public static JedisPool getRedisPool() {
//多线程时,jedisPool用锁
lockPool.lock();
try {
if (jedisPool == null) {
initialPool();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lockPool.unlock();
}
return jedisPool;
}
}
4、得到redis实例
import java.util.concurrent.locks.ReentrantLock;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisClient {
private static ReentrantLock lockJedis = new ReentrantLock();
private static JedisPool redisPool = null;
/**
* 获取redis实例
*/
public static Jedis getJedis() {
// 尝试获取redis实例锁,适用于高并发多线程场景
lockJedis.lock();
Jedis jedis = null;
try {
if (redisPool == null) {
redisPool = RedisPoolConfig.getRedisPool();
}
jedis = redisPool.getResource();
} catch (Exception e) {
e.printStackTrace();
} finally {
lockJedis.unlock();
}
return jedis;
}
/**
* 释放连接
*/
public static void closeJedis(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}
5、使用示例(适用于多线程)
import redis.clients.jedis.Jedis;
import java.io.IOException;
public class RedisUtil {
/**
* get String
* @param key
* @return
*/
public synchronized static String getString(String key) {
Jedis jedis = null;
try {
jedis = RedisClient.getJedis();
if (jedis == null) {
return null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
RedisClient.closeJedis(jedis);
}
return jedis.get(key);
}
/**
* set string
* @param key
* @param value
* @return
*/
public synchronized static String setString(String key,String value) {
Jedis jedis = null;
try {
jedis = RedisClient.getJedis();
if (jedis == null) {
return null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
RedisClient.closeJedis(jedis);
}
return jedis.set(key,value);
}
public static void main(String[] args) throws IOException {
setString("key", "value");
getString("key");
}
}