一、添加jedis的maven依赖
redis.clients
jedis
2.9.0
二、在配置cache.properties文件中配置单节点redis信息
# 单节点配置
redis.host = 127.0.0.1
redis.port = 6379
# 集群节点,集群模式下配置
#redis.cluster.nodes = 12.2.3.14:7001,12.2.3.14:7002,12.2.3.14:7003,12.2.3.14:7004
# 哨兵节点,哨兵模式下配置
#redis.sentinel.nodes = 12.2.3.14:7001,12.2.3.14:7002,12.2.3.14:7003,12.2.3.14:7004
#redis.sentinel.master = mymaster
# ----redis common begin----
# 密码
#redis.password = 123456
# 连接超时时间 单位 ms(毫秒)
redis.timeout = 6000
# 连接池中的最大空闲连接,默认值也是8
redis.pool.max-idle = 8
# 连接池中的最小空闲连接,默认值也是0
redis.pool.min-idle = 0
# 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
redis.pool.max-active = 8
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出
redis.pool.max-wait = -1
# ----redis common end----
三、定义CacheConfig类来加载配置信息
package com.ldy.common.cache;
/**
* @author lidongyang
* @Description 缓存配置类
* @date 2019/6/21 8:38
*/
public class CacheConfig {
/**
* 单节点REDIS 地址
*/
public static String REDIS_HOST = PropertiesUtils.getProperty("cache-config", "redis.host");
/**
* 单节点REDIS 端口
*/
public static int REDIS_PORT = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.port"));
/**
* 集群模式节点
*/
public static String REDIS_CLUSTER_NODES = PropertiesUtils.getProperty("cache-config", "redis.cluster.nodes");
/**
* 哨兵模式节点
*/
public static String REDIS_SENTINEL_NODES = PropertiesUtils.getProperty("cache-config", "redis.sentinel.nodes");
/**
* 哨兵模式 master
*/
public static String REDIS_SENTINEL_MASTER = PropertiesUtils.getProperty("cache-config", "redis.sentinel.master");
/**
* REDIS 密码
*/
public static String REDIS_PASSWORD = PropertiesUtils.getProperty("cache-config", "redis.password");
/**
* REDIS 连接超时时间 单位 ms(毫秒)
*/
public static int REDIS_TIMEOUT = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.timeout"));
/**
* 连接池中的最大空闲连接,默认值也是8
*/
public static int REDIS_POOL_MAX_IDLE = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.max-idle"));
/**
* 连接池中的最小空闲连接,默认值也是0
*/
public static int REDIS_POOL_MIN_IDLE = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.min-idle"));
/**
* # 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
*/
public static int REDIS_POOL_MAX_ACTIVE = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.max-active"));
/**
* 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出
*/
public static int REDIS_POOL_MAX_WAIT = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.max-wait"));
}
上面使用到的PropertiesUtils代码如下:
package com.ldy.common.cache;
import java.io.InputStream;
import java.util.Properties;
/**
*
* PropertiesUtils.java
* @desc properties 资源文件解析工具
* @author lidongyang
*
*/
public class PropertiesUtils {
private static Properties props;
private static void readProperties(String fileName) {
InputStream fis = null;
try {
props = new Properties();
fis =PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName);
props.load(fis);
} catch (Exception e) {
e.printStackTrace();
} finally{
if(fis != null){
try {
fis.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 根据文件名和属性名获取属性值
* @author lidongyang
* @param fileName
* @param key
* @return
*/
public synchronized static String getProperty(String fileName,String key){
readProperties(fileName+".properties");
return props.getProperty(key);
}
public static void main(String[] args) {
String value = PropertiesUtils.getProperty("webconfig", "zip_path");
System.out.println("value:"+value);
}
}
四、编写RedisSingleCache类用来操作redis
package com.ldy.common.cache;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.Date;
/**
* @author lidongyang
* @Description 单节点模式redis缓存接口
* @date 2019/6/20 16:38
*/
public class RedisSingleCache {
private static JedisPool jedisPool = null;
public RedisSingleCache() {
if (null == jedisPool) {
initPool();
}
}
private void initPool() {
JedisPoolConfig config = new JedisPoolConfig();
//最大连接数,如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
config.setMaxTotal(CacheConfig.REDIS_POOL_MAX_ACTIVE);
//最大空闲数,控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
config.setMaxIdle(CacheConfig.REDIS_POOL_MAX_IDLE);
//最小空闲数
config.setMinIdle(CacheConfig.REDIS_POOL_MIN_IDLE);
//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
config.setMaxWaitMillis(CacheConfig.REDIS_POOL_MAX_WAIT);
//是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
config.setTestOnBorrow(true);
//在return给pool时,是否提前进行validate操作
config.setTestOnReturn(true);
//在空闲时检查有效性,默认false
config.setTestWhileIdle(true);
if (null == CacheConfig.REDIS_PASSWORD || CacheConfig.REDIS_PASSWORD == "") {
jedisPool = new JedisPool(config, CacheConfig.REDIS_HOST, CacheConfig.REDIS_PORT, CacheConfig.REDIS_TIMEOUT);
} else {
jedisPool = new JedisPool(config, CacheConfig.REDIS_HOST, CacheConfig.REDIS_PORT, CacheConfig.REDIS_TIMEOUT, CacheConfig.REDIS_PASSWORD);
}
}
/**
* 同步获取Jedis实例
*
* @return Jedis
*/
private synchronized static Jedis getJedis() {
return jedisPool.getResource();
}
public String get(String key) {
Jedis jedis = getJedis();
if (jedis == null) {
System.out.println("Jedis实例获取失败!");
throw new RuntimeException();
}
try {
return jedis.get(key);
} catch (Exception e) {
System.out.println("获取值失败:" + e.getMessage());
throw new RuntimeException();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
public Object getObject(String key) {
Jedis jedis = getJedis();
if (jedis == null) {
System.out.println("Jedis实例获取失败!");
throw new RuntimeException();
}
try {
byte[] data = jedis.get(key.getBytes());
return SerializeUtils.unserialize(data);
} catch (Exception e) {
System.out.println("获取值失败:" + e.getMessage());
throw new RuntimeException();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
public void set(String key, String value) {
Jedis jedis = getJedis();
try {
jedis.set(key, value);
} catch (Exception e) {
System.out.println("设置值失败:" + e.getMessage());
throw new RuntimeException();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
public void set(String key, String value, int second) {
Jedis jedis = getJedis();
try {
jedis.set(key, value);
jedis.expire(key, second);
} catch (Exception e) {
System.out.println("设置值失败:" + e.getMessage());
throw new RuntimeException();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
public void setObject(String key, Object value) {
Jedis jedis = getJedis();
try {
jedis.set(key.getBytes(), SerializeUtils.serialize(value));
} catch (Exception e) {
System.out.println("设置值失败:" + e.getMessage());
throw new RuntimeException();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
public void setObject(String key, Object value, int second) {
Jedis jedis = getJedis();
try {
jedis.set(key.getBytes(), SerializeUtils.serialize(value));
jedis.expire(key, second);
} catch (Exception e) {
System.out.println("设置值失败:" + e.getMessage());
throw new RuntimeException();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
public void del(String key) {
Jedis jedis = getJedis();
try {
jedis.del(key);
} catch (Exception e) {
System.out.println("删除失败:" + e.getMessage());
throw new RuntimeException();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
public static void main(String[] args) {
RedisSingleCache cache = new RedisSingleCache();
cache.set("lisi", "李四");
System.out.println(cache.get("lisi"));
cache.del("lisi");
cache.setObject("date", new Date());
System.out.println(cache.getObject("date"));
}
}
辅助工具类SerializeUtils代码如下
package com.ldy.common.cache;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @author lidongyang
* @Description 对象序列化工具类
* @date 2019/6/20 18:51
*/
public class SerializeUtils {
/**
* 序列化
* @param obj
* @return
*/
public static byte[] serialize(Object obj) {
ByteArrayOutputStream byteOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
byteOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteOutputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
return byteOutputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != objectOutputStream) {
try {
objectOutputStream.close();
byteOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 反序列化
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream byteInputStream = null;
ObjectInputStream objectInputStream = null;
try {
byteInputStream = new ByteArrayInputStream(bytes);
objectInputStream = new ObjectInputStream(byteInputStream);
return objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != objectInputStream) {
try {
objectInputStream.close();
byteInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
}