1.加入gogole提供的工具包(序列化会用到)+redis包
com.google.guava
guava
18.0
org.springframework.boot
spring-boot-starter-data-redis
com.dyuproject.protostuff
protostuff-core
1.1.3
com.dyuproject.protostuff
protostuff-runtime
1.1.3
2.自己编写序列化工具
@Slf4j
public class ProtoStuffUtil {
/**
* 序列化对象
*
* @param obj
* @return
*/
public static byte[] serialize(T obj) {
if (obj == null) {
log.error("Failed to serializer, obj is null");
throw new RuntimeException("Failed to serializer");
}
@SuppressWarnings("unchecked") Schema schema = (Schema) RuntimeSchema.getSchema(obj.getClass());
LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
byte[] protoStuff;
try {
protoStuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
log.error("Failed to serializer, obj:{}", obj, e);
throw new RuntimeException("Failed to serializer");
} finally {
buffer.clear();
}
return protoStuff;
}
/**
* 反序列化对象
*
* @param paramArrayOfByte
* @param targetClass
* @return
*/
public static T deserialize(byte[] paramArrayOfByte, Class targetClass) {
if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
log.error("Failed to deserialize, byte is empty");
throw new RuntimeException("Failed to deserialize");
}
T instance;
try {
instance = targetClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
log.error("Failed to deserialize", e);
throw new RuntimeException("Failed to deserialize");
}
Schema schema = RuntimeSchema.getSchema(targetClass);
ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema);
return instance;
}
/**
* 序列化列表
*
* @param objList
* @return
*/
public static byte[] serializeList(List objList) {
if (objList == null || objList.isEmpty()) {
log.error("Failed to serializer, objList is empty");
throw new RuntimeException("Failed to serializer");
}
@SuppressWarnings("unchecked") Schema schema =
(Schema) RuntimeSchema.getSchema(objList.get(0).getClass());
LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
byte[] protoStuff;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer);
protoStuff = bos.toByteArray();
} catch (Exception e) {
log.error("Failed to serializer, obj list:{}", objList, e);
throw new RuntimeException("Failed to serializer");
} finally {
buffer.clear();
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return protoStuff;
}
/**
* 反序列化列表
*
* @param paramArrayOfByte
* @param targetClass
* @return
*/
public static List deserializeList(byte[] paramArrayOfByte, Class targetClass) {
if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
log.error("Failed to deserialize, byte is empty");
throw new RuntimeException("Failed to deserialize");
}
Schema schema = RuntimeSchema.getSchema(targetClass);
List result;
try {
result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema);
} catch (IOException e) {
log.error("Failed to deserialize", e);
throw new RuntimeException("Failed to deserialize");
}
return result;
}
}
3.RedisTemplate的工具类方法
@Component
public class RedisClient {
private final RedisTemplate redisTemplate;
@Autowired
public RedisClient(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* get cache
*
* @param field
* @param targetClass
* @param
* @return
*/
public T get(final String field, Class targetClass) {
byte[] result = redisTemplate.execute((RedisCallback) connection -> connection.get(field.getBytes()));
if (result == null) {
return null;
}
return ProtoStuffUtil.deserialize(result, targetClass);
}
/**
* put cache
*
* @param field
* @param obj
* @param
* @return
*/
public void set(String field, T obj) {
final byte[] value = ProtoStuffUtil.serialize(obj);
redisTemplate.execute((RedisCallback) connection -> {
connection.set(field.getBytes(), value);
return null;
});
}
/**
* put cache with expire time
*
* @param field
* @param obj
* @param expireTime 单位: s
* @param
*/
public void setWithExpire(String field, T obj, final long expireTime) {
final byte[] value = ProtoStuffUtil.serialize(obj);
redisTemplate.execute((RedisCallback) connection -> {
connection.setEx(field.getBytes(), expireTime, value);
return null;
});
}
/**
* get list cache
*
* @param field
* @param targetClass
* @param
* @return
*/
public List getList(final String field, Class targetClass) {
byte[] result = redisTemplate.execute((RedisCallback) connection -> connection.get(field.getBytes()));
if (result == null) {
return null;
}
return ProtoStuffUtil.deserializeList(result, targetClass);
}
/**
* put list cache
*
* @param field
* @param objList
* @param
* @return
*/
public void setList(String field, List objList) {
final byte[] value = ProtoStuffUtil.serializeList(objList);
redisTemplate.execute((RedisCallback) connection -> {
connection.set(field.getBytes(), value);
return null;
});
}
/**
* put list cache with expire time
*
* @param field
* @param objList
* @param expireTime
* @param
* @return
*/
public void setListWithExpire(String field, List objList, final long expireTime) {
final byte[] value = ProtoStuffUtil.serializeList(objList);
redisTemplate.execute((RedisCallback) connection -> {
connection.setEx(field.getBytes(), expireTime, value);
return null;
});
}
/**
* get h cache
*
* @param key
* @param field
* @param targetClass
* @param
* @return
*/
public T hGet(final String key, final String field, Class targetClass) {
byte[] result = redisTemplate
.execute((RedisCallback) connection -> connection.hGet(key.getBytes(), field.getBytes()));
if (result == null) {
return null;
}
return ProtoStuffUtil.deserialize(result, targetClass);
}
/**
* put hash cache
*
* @param key
* @param field
* @param obj
* @param
* @return
*/
public boolean hSet(String key, String field, T obj) {
final byte[] value = ProtoStuffUtil.serialize(obj);
return redisTemplate.execute(
(RedisCallback) connection -> connection.hSet(key.getBytes(), field.getBytes(), value));
}
/**
* put hash cache
*
* @param key
* @param field
* @param obj
* @param
*/
public void hSetWithExpire(String key, String field, T obj, long expireTime) {
final byte[] value = ProtoStuffUtil.serialize(obj);
redisTemplate.execute((RedisCallback) connection -> {
connection.hSet(key.getBytes(), field.getBytes(), value);
connection.expire(key.getBytes(), expireTime);
return null;
});
}
/**
* get list cache
*
* @param key
* @param field
* @param targetClass
* @param
* @return
*/
public List hGetList(final String key, final String field, Class targetClass) {
byte[] result = redisTemplate
.execute((RedisCallback) connection -> connection.hGet(key.getBytes(), field.getBytes()));
if (result == null) {
return null;
}
return ProtoStuffUtil.deserializeList(result, targetClass);
}
/**
* put list cache
*
* @param key
* @param field
* @param objList
* @param
* @return
*/
public boolean hSetList(String key, String field, List objList) {
final byte[] value = ProtoStuffUtil.serializeList(objList);
return redisTemplate.execute(
(RedisCallback) connection -> connection.hSet(key.getBytes(), field.getBytes(), value));
}
/**
* get cache by keys
*
* @param key
* @param fields
* @param targetClass
* @param
* @return
*/
public Map hMGet(String key, Collection fields, Class targetClass) {
List byteFields = fields.stream().map(String::getBytes).collect(Collectors.toList());
byte[][] queryFields = new byte[byteFields.size()][];
byteFields.toArray(queryFields);
List cache = redisTemplate
.execute((RedisCallback>) connection -> connection.hMGet(key.getBytes(), queryFields));
Map results = new HashMap<>(16);
Iterator it = fields.iterator();
int index = 0;
while (it.hasNext()) {
String k = it.next();
if (cache.get(index) == null) {
index++;
continue;
}
results.put(k, ProtoStuffUtil.deserialize(cache.get(index), targetClass));
index++;
}
return results;
}
/**
* set cache by keys
*
* @param field
* @param values
* @param
*/
public void hMSet(String field, Map values) {
Map byteValues = new HashMap<>(16);
for (Map.Entry value : values.entrySet()) {
byteValues.put(value.getKey().getBytes(), ProtoStuffUtil.serialize(value.getValue()));
}
redisTemplate.execute((RedisCallback) connection -> {
connection.hMSet(field.getBytes(), byteValues);
return null;
});
}
/**
* get caches in hash
*
* @param key
* @param targetClass
* @param
* @return
*/
public Map hGetAll(String key, Class targetClass) {
Map records = redisTemplate
.execute((RedisCallback