RedisUtil工具類封裝
阿新 • • 發佈:2019-01-10
Redis有很多資料結構:string、hash、list、set等,但是在實際來發中,我們往往儲存的是物件在redis中,所以鍵值對更加常用。
Redis在儲存物件時,需要滿足序列化,由於java的原生序列化方式效率較低,故更加常用的是Protostuff這個序列化框架。 |
一、封裝Protostuff工具類
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
public class SerializeUtil {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
public static <T> byte[] serializer (T obj) {
Class<T> clazz = (Class<T>) obj.getClass();
Schema<T> schema = getSchema(clazz);
return ProtobufIOUtil.toByteArray(obj, schema, LinkedBuffer.allocate(256));
}
public static <T> T deSerializer(byte[] bytes, Class<T> clazz) {
T message;
try {
message = clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
Schema<T> schema = getSchema(clazz);
ProtobufIOUtil.mergeFrom(bytes, message, schema);
return message;
}
@SuppressWarnings("unchecked")
public static <T> Schema<T> getSchema(Class<T> clazz) {
Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
if (schema == null) {
schema = RuntimeSchema.createFrom(clazz);
if (schema != null) {
cachedSchema.put(clazz, schema);
}
}
return schema;
}
}
二、封裝RedisUtil工具類
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
private static String ADDR = "localhost";
private static int PORT = 6379;
private static String AUTH = "123456";
// 最大連線例項數,預設為8,-1表示無限制,如果pool已經分配了超過max_active個jedis例項,則此時pool為耗盡
private static int MAX_ACTIVE = 1024;
// 最大空閒例項,預設為8
private static int MAX_IDLE = 200;
// 最大等待連線時間,單位毫秒預設為-1,表示永不超時,超時會丟擲JedisConnectionException
private static int MAX_WAIT = 10 * 1000;
private static int TIMEOUT = 10 * 1000;
// 在borrow一個jedis例項時,是否提前進行validate操作,如果為true,則得到的jedis例項均是可用的
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
/**
* 初始化連線池
*/
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
}
/**
* 獲取jedis例項
*/
public synchronized static Jedis getJedis() {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
}
return null;
}
/**
* 釋放資源
*
* @param jedis
*/
public static void close(final Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
/**
* 儲存物件(鍵-值)
*
* @param <T>
*
* @param key
* @param object
* @return
*/
public static <T> String setObject(String key, T object) {
Jedis jedis = getJedis();
try {
return jedis.set(key.getBytes(), SerializeUtil.serializer(object));
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
close(jedis);
}
}
/**
* 帶時間儲存(鍵值)
*
* @param key
* @param object
* @param expiretime
* @return
*/
public static <T> String setObject(String key, T object, long expiretime) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.psetex(key.getBytes(), expiretime, SerializeUtil.serializer(object));
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
close(jedis);
}
}
/**
* 讀取物件(鍵-值)
*
* @param key
* @param clazz
* @return
*/
public static <T> T getObject(String key, Class<T> clazz) {
Jedis jedis = getJedis();
try {
byte[] bytes = jedis.get(key.getBytes());
T object = SerializeUtil.deSerializer(bytes, clazz);
return object;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
close(jedis);
}
}
/**
* 刪除key
*/
public static Long deleteObject(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.del(key.getBytes());
} catch (Exception e) {
return null;
} finally {
close(jedis);
}
}
/**
* 檢查存在
*
* @param key
* @return
*/
public static Boolean existsObject(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.exists(key.getBytes());
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
close(jedis);
}
}
}
三、測試
User:
public class User{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
Main:
public class Main {
public static void main(String[] args) {
User user = new User();
user.setName("旭旭寶寶");
user.setAge(33);
RedisUtil.setObject("user", user);
User obj = RedisUtil.getObject("user", User.class);
System.out.println(obj);
System.out.println(RedisUtil.existsObject("user"));
}
}