package com.cares.mbsis.redis.service;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.cares.mbsis.redis.util.ProtobuffSerializationUtil;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
@Service("redisService")
public class RedisService {
private static final Logger log = Logger.getLogger(RedisService.class);
@Autowired
private ShardedJedisPool shardedJedisPool;
/**
* @param key
* @param value
* @return
* 设置单个值
*/
public String set(String key,Object value){
String result = null;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if(shardedJedis == null){
return result;
}
try {
result = shardedJedis.set(key,new String(ProtobuffSerializationUtil.serialize(value),"ISO-8859-1"));
} catch (Exception e) {
log.error(e.getMessage(),e);
} finally{
shardedJedis.close();
}
return result;
}
/**
* @param key
* @param value
* @return
* 设置List
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public String setList(String key,List value){
String result = null;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if(shardedJedis == null){
return result;
}
try {
result = shardedJedis.set(key,new String(ProtobuffSerializationUtil.serializeList(value),"ISO-8859-1"));
} catch (Exception e) {
log.error(e.getMessage(),e);
} finally{
shardedJedis.close();
}
return result;
}
/**
* @param key
* @param value
* @return
* 设置单个值和有效时间
*/
public String set(String key,Object value,int seconds){
String result = null;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if(shardedJedis == null){
return result;
}
try {
result = shardedJedis.set(key,new String(ProtobuffSerializationUtil.serialize(value),"ISO-8859-1"));
expire(key, seconds);
} catch (Exception e) {
log.error(e.getMessage(),e);
} finally{
shardedJedis.close();
}
return result;
}
/**
* @param key
* @param value
* @return
* 设置List和有效时间
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public String setList(String key,List value,int seconds){
String result = null;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if(shardedJedis == null){
return result;
}
try {
result = shardedJedis.set(key,new String(ProtobuffSerializationUtil.serializeList(value),"ISO-8859-1"));
expire(key, seconds);
} catch (Exception e) {
log.error(e.getMessage(),e);
} finally{
shardedJedis.close();
}
return result;
}
/**
* @param key
* @param value
* @return
* 获取单个值
*/
public <T> T get(String key,Class<T> clazz){
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if(shardedJedis == null){
return null;
}
try {
String resultStr = shardedJedis.get(key);
if(StringUtils.isEmpty(resultStr))
return null;
return ProtobuffSerializationUtil.deserialize(resultStr.getBytes("ISO-8859-1"), clazz);
} catch (Exception e) {
log.error(e.getMessage(),e);
e.printStackTrace();
} finally{
shardedJedis.close();
}
return null;
}
/**
* @param key
* @param value
* @return
* 获取List
*/
public <T> List<T> getList(String key,Class<T> clazz){
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if(shardedJedis == null){
return null;
}
try {
String resultStr = shardedJedis.get(key);
if(StringUtils.isEmpty(resultStr))
return null;
return ProtobuffSerializationUtil.deserializeList(resultStr.getBytes("ISO-8859-1"), clazz);
} catch (Exception e) {
log.error(e.getMessage(),e);
e.printStackTrace();
} finally{
shardedJedis.close();
}
return null;
}
/**
* @param key
* @param value
* @return
* 判断key是否存在
*/
public Boolean exists(String key){
Boolean result = false;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if(shardedJedis == null){
return result;
}
try {
result = shardedJedis.exists(key);
} catch (Exception e) {
log.error(e.getMessage(),e);
} finally{
shardedJedis.close();
}
return result;
}
/**
* @param key
* @param value
* @return
* 设置key的过期时间段
*/
public Long expire(String key,int seconds){
Long result = null;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if(shardedJedis == null){
return result;
}
try {
result = shardedJedis.expire(key, seconds);
} catch (Exception e) {
log.error(e.getMessage(),e);
} finally{
shardedJedis.close();
}
return result;
}
/**
* @param key
* @param value
* @return
* 设置key的过期时间点
*/
public Long expire(String key,long unixTime){
Long result = null;
ShardedJedis shardedJedis = shardedJedisPool.getResource();
if(shardedJedis == null){
return result;
}
try {
result = shardedJedis.expireAt(key, unixTime);
} catch (Exception e) {
log.error(e.getMessage(),e);
} finally{
shardedJedis.close();
}
return result;
}
}
四、序列反序列工具类ProtobuffSerializationUtil.java
package com.cares.mbsis.redis.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.objenesis.Objenesis;
import org.springframework.objenesis.ObjenesisStd;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
/**
* @Description:Protobuff插件序列化
*/
public class ProtobuffSerializationUtil {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
private static Objenesis objenesis = new ObjenesisStd(true);
public static<T> Schema<T> getSchema(Class<T> clazz){
@SuppressWarnings("unchecked")
Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
if (schema == null) {
schema = RuntimeSchema.getSchema(clazz);
if (schema != null) {
cachedSchema.put(clazz, schema);
}
}
return schema;
}
/**
* 序列化
*
* @param obj
* @return
*/
public static <T> byte[] serialize(T obj) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer
.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(clazz);
return ProtobufIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
/**
* 序列化List
*
* @param obj
* @return
*/
public static <T> byte[] serializeList(List<T> objList) {
if(objList == null || objList.isEmpty()){
throw new RuntimeException("序列化对象列表("+objList+")参数异常!");
}
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) objList.get(0).getClass();
LinkedBuffer buffer = LinkedBuffer
.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
byte[] protostuff = null;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
Schema<T> schema = getSchema(clazz);
ProtostuffIOUtil.writeListTo(bos,objList,schema,buffer);
protostuff = bos.toByteArray();
return protostuff;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
/**
* 反序列化
*
* @param data
* @param clazz
* @return
*/
public static <T> T deserialize(byte[] data, Class<T> clazz) {
try {
T obj = objenesis.newInstance(clazz);
Schema<T> schema = getSchema(clazz);
ProtobufIOUtil.mergeFrom(data, obj, schema);
return obj;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
/**
* 反序列化List
*
* @param data
* @param clazz
* @return
*/
public static <T> List<T> deserializeList(byte[] data, Class<T> clazz) {
if(data == null || data.length == 0){
throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
}
try {
Schema<T> schema = getSchema(clazz);
List<T> result = null;
result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(data),schema);
return result;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
五、key生成工具类GenerateKeyUtil.java
package com.cares.mbsis.redis.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.log4j.Logger;
import sun.misc.BASE64Encoder;
public class GenerateKeyUtil {
private static final Logger log = Logger.getLogger(GenerateKeyUtil.class);
/**
* @param t
* @param parm
* @return
* @throws NoSuchAlgorithmException
* 生成key供redis入库
**/
@SuppressWarnings("static-access")
public synchronized static String generateKey(Thread t,String parms){
StringBuffer key = new StringBuffer();
String resultKey = null;
key.append(t.currentThread().getStackTrace()[1].getClassName())
.append(t.currentThread().getStackTrace()[1].getMethodName())
.append(t.currentThread().getStackTrace()[1].getLineNumber())
.append(parms);
MessageDigest md;
try {
md = MessageDigest.getInstance("md5");
byte md5[] = md.digest(key.toString().getBytes());
//base64编码--任意二进制编码明文字符
BASE64Encoder encoder = new BASE64Encoder();
resultKey = encoder.encode(md5);
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(),e);
}
return resultKey;
}
/**
* @param t
* @param parm
* @return
* @throws NoSuchAlgorithmException
* 生成key供redis入库
**/
public synchronized static String generateKey(Thread t){
return generateKey(t,"");
}
}
六、ReportController.java应用Redis缓存
package com.cares.mbsis.web.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import com.cares.mbsis.redis.service.RedisService;
import com.cares.mbsis.redis.util.GenerateKeyUtil;
import com.cares.mbsis.service.ReportService;
import com.cares.mbsis.util.Constants;
import com.cares.mbsis.util.Util;
@Controller
public class ReportController {
@Autowired
private ReportService reportService;
@Autowired
private RedisService redisService;
@RequestMapping(value="getOrderDistribution.do",method = RequestMethod.POST)
@ResponseBody
public ModelAndView getOrderDistribution() throws IOException{
Map<String, String> map = new HashMap<String, String>();
String jsonStr = null;
String key = GenerateKeyUtil.generateKey(Thread.currentThread());
jsonStr = redisService.get(key,String.class);
if(Util.isNull(jsonStr)){
jsonStr = reportService.getOrderDistribution();
redisService.set(key,jsonStr,1*Constants.HOUR);
}
map.put("msg",jsonStr);
return new ModelAndView(new MappingJackson2JsonView(),map);
}
}