You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

132 lines
3.3 KiB

package com.stone.conf.redis;
import redis.clients.jedis.Jedis;
import java.io.*;
/**
* redis 序列化辅助类
*
* @author zhoujl
* @date 2019-04-30
*/
public class RedisHelper {
/**
* 添加缓存信息
*/
public static void add(String key, Object value) {
Jedis jedis = new Jedis("localhost");
try {
jedis.set(key.getBytes(), ObjectTranscoder.serialize(value));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取缓存信息
*/
public static Object get(String key) {
Jedis jedis = new Jedis("localhost");
if (!jedis.exists(key.getBytes())) {
return null;
}
byte[] in = jedis.get(key.getBytes());
return ObjectTranscoder.deserialize(in);
}
/**
* 判断 key 是否存在
*
* @param key 键信息
* @return 是否存在
*/
public static Boolean exists(String key) {
Jedis jedis = new Jedis("localhost");
return jedis.exists(key.getBytes());
}
/**
* 删除key
*
* @param key 键信息
*/
public static void delKey(String key) {
Jedis jedis = new Jedis("localhost");
jedis.del(key.getBytes());
}
static class ObjectTranscoder {
/**
* 序列化参数
*
* @param value object
* @return byte
*/
static byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("参数不能为空");
}
byte[] rv;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(value);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("该对象不可序列化", e);
} finally {
try {
if (os != null)
os.close();
if (bos != null)
bos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}
/**
* 反序列化参数
*
* @param in byte
* @return object
*/
static Object deserialize(byte[] in) {
Object rv = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
rv = is.readObject();
is.close();
bis.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
if (bis != null)
bis.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}
}
}