版本要求:3.5.2支持 jdk7, 从3.6.0 开始,需要jdk8
一 导入jedis.jar包
如果找不jar包,https://mvnrepository.com/从这个网站下载,搜索,找到需要的版本,下载。
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.2.3</version>
</dependency>
</dependencies>
二 JedisUtil工具类
注意:如果JedisPoolConfig.set报错,还得导入commons-pool这个jar包,因为高版本jedis没用集成进去。
/**
* JedisUtil(推荐存Byte数组,存Json字符串效率更慢)
* @author hhc
*/
public class JedisUtil {
private static volatile JedisPool jedisPool = null;
/**
* 初始化Redis连接池
*/
static {
try {
System.out.println("初始化成功");
if (null == jedisPool) {
synchronized (JedisUtil.class) {
if (null == jedisPool) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(1000);
poolConfig.setMaxIdle(32);
poolConfig.setMaxWaitMillis(100 * 1000);
poolConfig.setTestOnBorrow(true);
jedisPool = new JedisPool(poolConfig, "127.0.0.1", 6379);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取Jedis实例
* @param
* @return redis.clients.jedis.Jedis
* @author dvy.com.cn
* @date 2022/7/4 15:47
*/
public static synchronized Jedis getJedis() {
try {
if (jedisPool != null) {
return jedisPool.getResource();
} else {
return null;
}
} catch (Exception e) {
throw new RuntimeException("获取Jedis资源异常:" + e.getMessage());
}
}
/**
* 释放Jedis资源
* @param
* @return void
* @author dvy.com.cn
* @date 2022/7/4 9:16
*/
public static void closePool() {
try {
jedisPool.close();
} catch (Exception e) {
throw new RuntimeException("释放Jedis资源异常:" + e.getMessage());
}
}
/**
* 获取redis键值-object
* @param key
* @return java.lang.Object
* @author dvy.com.cn
* @date 2022/7/4 15:47
*/
public static Object getObject(String key) {
try (Jedis jedis = jedisPool.getResource()) {
byte[] bytes = jedis.get(key.getBytes());
if (StringUtil.isNotNull(bytes)) {
return SerializableUtil.unserializable(bytes);
}
} catch (Exception e) {
throw new RuntimeException("获取Redis键值getObject方法异常:key=" + key + " cause=" + e.getMessage());
}
return null;
}
/**
* 设置redis键值-object
* @param key
* @param value
* @return java.lang.String
* @author dvy.com.cn
* @date 2022/7/4 15:49
*/
public static String setObject(String key, Object value) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.set(key.getBytes(), SerializableUtil.serializable(value));
} catch (Exception e) {
throw new RuntimeException("设置Redis键值setObject方法异常:key=" + key + " value=" + value + " cause=" + e.getMessage());
}
}
/**
* 设置redis键值-object-expiretime
* @param key
* @param value
* @param expiretime
* @return java.lang.String
* @author dvy.com.cn
* @date 2022/7/4 15:50
*/
public static String setObject(String key, Object value, int expiretime) {
String result;
try (Jedis jedis = jedisPool.getResource()) {
result = jedis.set(key.getBytes(), SerializableUtil.serializable(value));
if (Constant.OK.equals(result)) {
jedis.expire(key.getBytes(), expiretime);
}
return result;
} catch (Exception e) {
throw new RuntimeException("设置Redis键值setObject方法异常:key=" + key + " value=" + value + " cause=" + e.getMessage());
}
}
/**
* 获取redis键值-Json
* @param key
* @return java.lang.Object
* @author dvy.com.cn
* @date 2022/7/4 15:47
*/
public static String getJson(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.get(key);
} catch (Exception e) {
throw new RuntimeException("获取Redis键值getJson方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* 设置redis键值-Json
* @param key
* @param value
* @return java.lang.String
* @author Wang926454
* @date 2022/7/4 15:49
*/
public static String setJson(String key, String value) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.set(key, value);
} catch (Exception e) {
throw new RuntimeException("设置Redis键值setJson方法异常:key=" + key + " value=" + value + " cause=" + e.getMessage());
}
}
/**
* 设置redis键值-Json-expiretime
* @param key
* @param value
* @param expiretime
* @return java.lang.String
* @author dvy.com.cn
* @date 2022/7/4 15:50
*/
public static String setJson(String key, String value, int expiretime) {
String result;
try (Jedis jedis = jedisPool.getResource()) {
result = jedis.set(key, value);
if (Constant.OK.equals(result)) {
jedis.expire(key, expiretime);
}
return result;
} catch (Exception e) {
throw new RuntimeException("设置Redis键值setJson方法异常:key=" + key + " value=" + value + " cause=" + e.getMessage());
}
}
/**
* 删除key
* @param key
* @return java.lang.Long
* @author dvy.com.cn
* @date 2022/7/4 15:50
*/
public static Long delKey(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.del(key.getBytes());
} catch (Exception e) {
throw new RuntimeException("删除Redis的键delKey方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* key是否存在
* @param key
* @return java.lang.Boolean
* @author dvy.com.cn
* @date 2022/7/4 15:51
*/
public static Boolean exists(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.exists(key.getBytes());
} catch (Exception e) {
throw new RuntimeException("查询Redis的键是否存在exists方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* 模糊查询获取key集合(keys的速度非常快,但在一个大的数据库中使用它仍然可能造成性能问题,生产不推荐使用)
* @param key
* @return java.util.Set<java.lang.String>
* @author dvy.com.cn
* @date 2022/7/4 9:43
*/
public static Set<String> keysS(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.keys(key);
} catch (Exception e) {
throw new RuntimeException("模糊查询Redis的键集合keysS方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* 模糊查询获取key集合(keys的速度非常快,但在一个大的数据库中使用它仍然可能造成性能问题,生产不推荐使用)
* @param key
* @return java.util.Set<java.lang.String>
* @author Wang926454
* @date 2018/9/6 9:43
*/
public static Set<byte[]> keysB(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.keys(key.getBytes());
} catch (Exception e) {
throw new RuntimeException("模糊查询Redis的键集合keysB方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* 获取过期剩余时间
* @param key
* @return java.lang.String
* @author dvy.com.cn
* @date 2022/7/4 16:26
*/
public static Long ttl(String key) {
Long result = -2L;
try (Jedis jedis = jedisPool.getResource()) {
result = jedis.ttl(key);
return result;
} catch (Exception e) {
throw new RuntimeException("获取Redis键过期剩余时间ttl方法异常:key=" + key + " cause=" + e.getMessage());
}
}
}
三 序列化工具类
/**
* Serializable工具(JDK)(也可以使用Protobuf自行百度)
* @author hhc
*/
public class SerializableUtil {
private SerializableUtil() {}
/**
* logger
*/
private static final Logger logger = LoggerFactory.getLogger(SerializableUtil.class);
/**
* 序列化
* @param object
* @return byte[]
* @author dvy.com.cn
* @date 2022/7/4 15:14
*/
public static byte[] serializable(Object object) {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
return baos.toByteArray();
} catch (IOException e) {
logger.error("SerializableUtil工具类序列化出现IOException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类序列化出现IOException异常:" + e.getMessage());
} finally {
try {
if (oos != null) {
oos.close();
}
if (baos != null) {
baos.close();
}
} catch (IOException e) {
logger.error("SerializableUtil工具类反序列化出现IOException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
}
}
}
/**
* 反序列化
* @param bytes
* @return java.lang.Object
* @author dvy.com.cn
* @date 2022/7/4 15:14
*/
public static Object unserializable(byte[] bytes) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (ClassNotFoundException e) {
logger.error("SerializableUtil工具类反序列化出现ClassNotFoundException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类反序列化出现ClassNotFoundException异常:" + e.getMessage());
} catch (IOException e) {
logger.error("SerializableUtil工具类反序列化出现IOException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
} finally {
try {
if (ois != null) {
ois.close();
}
if (bais != null) {
bais.close();
}
} catch (IOException e) {
logger.error("SerializableUtil工具类反序列化出现IOException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
}
}
}
}
四 通用的工具包
自己可以导入,或者替换掉
public class StringUtil {
private StringUtil() {}
/**
* 定义下划线
*/
private static final char UNDERLINE = '_';
/**
* String为空判断(不允许空格)
* @param str
* @return boolean
* @author dvy.com.cn
* @date 2022/7/4 14:49
*/
public static boolean isBlank(String str) {
return str == null || "".equals(str.trim());
}
/**
* String不为空判断(不允许空格)
* @param str
* @return boolean
* @author dvy.com.cn
* @date 2022/7/4 14:51
*/
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
/**
* Byte数组为空判断
* @param bytes
* @return boolean
* @author dvy.com.cn
* @date 2022/7/4 15:39
*/
public static boolean isNull(byte[] bytes) {
// 根据byte数组长度为0判断
return bytes == null || bytes.length == 0;
}
/**
* Byte数组不为空判断
* @param bytes
* @return boolean
* @author dvy.com.cn
* @date 2022/7/4 15:41
*/
public static boolean isNotNull(byte[] bytes) {
return !isNull(bytes);
}
/**
* 驼峰转下划线工具
* @param param
* @return java.lang.String
* @author dvy.com.cn
* @date 2022/7/4 14:52
*/
public static String camelToUnderline(String param) {
if (isNotBlank(param)) {
int len = param.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(UNDERLINE);
sb.append(Character.toLowerCase(c));
} else {
sb.append(c);
}
}
return sb.toString();
} else {
return "";
}
}
/**
* 下划线转驼峰工具
* @param param
* @return java.lang.String
* @author dvy.com.cn
* @date 2022/7/4 14:52
*/
public static String underlineToCamel(String param) {
if (isNotBlank(param)) {
int len = param.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (c == 95) {
i++;
if (i < len) {
sb.append(Character.toUpperCase(param.charAt(i)));
}
} else {
sb.append(c);
}
}
return sb.toString();
} else {
return "";
}
}
/**
* 在字符串两周添加''
* @param param
* @return java.lang.String
* @author dvy.com.cn
* @date 2022/7/4 14:53
*/
public static String addSingleQuotes(String param) {
return "\'" + param + "\'";
}
}
public class Constant {
private Constant() {}
/**
* redis-OK
*/
public static final String OK = "OK";
/**
* redis过期时间,以秒为单位,一分钟
*/
public static final int EXRP_MINUTE = 60;
/**
* redis过期时间,以秒为单位,一小时
*/
public static final int EXRP_HOUR = 60 * 60;
/**
* redis过期时间,以秒为单位,一天
*/
public static final int EXRP_DAY = 60 * 60 * 24;
/**
* redis-key-前缀-shiro:cache:
*/
public static final String PREFIX_SHIRO_CACHE = "shiro:cache:";
/**
* redis-key-前缀-shiro:access_token:
*/
public static final String PREFIX_SHIRO_ACCESS_TOKEN = "shiro:access_token:";
/**
* redis-key-前缀-shiro:refresh_token:
*/
public static final String PREFIX_SHIRO_REFRESH_TOKEN = "shiro:refresh_token:";
/**
* JWT-account:
*/
public static final String ACCOUNT = "account";
/**
* JWT-currentTimeMillis:
*/
public static final String CURRENT_TIME_MILLIS = "currentTimeMillis";
/**
* PASSWORD_MAX_LEN
*/
public static final Integer PASSWORD_MAX_LEN = 8;
}
五 使用jedis
注意:实例化bean要存jedis,一定需要实现Serializable接口,否则报错。关于各种类型的使用,查询官网。
public class ServiceObject implements Serializable {
List<ServiceObject> sos1 = null;
if(!JedisUtil.exists("ServiceObject1")){
System.out.println("查询,设置redis");
sos1 = objectDao.selectByCreateDate(temp);
String isOk2 = JedisUtil.setObject("ServiceObject1", sos1);
if("OK".equals(isOk2)){
System.out.println("设置成功:" + isOk2);
}
}else {
System.out.println("从redis获取");
sos1 = (List<ServiceObject>)JedisUtil.getObject("ServiceObject1");
}
}