设为首页 收藏本站
查看: 1038|回复: 0

[经验分享] Spring+Jedis+Redis自定义模板实现缓存Object对象

[复制链接]

尚未签到

发表于 2016-12-21 06:37:44 | 显示全部楼层 |阅读模式
  在实际使用缓存的过程中,我们希望放入缓存的并不是一个String类型参数而是一个Object对象,而且希望从缓存中取出的也是一个Object对象

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:task="http://www.springframework.org/schema/task" xmlns:util="http://www.springframework.org/schema/util"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/task  
http://www.springframework.org/schema/task/spring-task-3.1.xsd  
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
">
<aop:aspectj-autoproxy />
<context:annotation-config />
<context:component-scan base-package="com.cathy.demo.redis.*" />
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="127.0.0.1" />
<constructor-arg name="port" value="6379" />
<constructor-arg name="timeout" value="2000" />
</bean>
</list>
</constructor-arg>
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="50" />
<property name="maxIdle" value="8" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
</bean>
<bean id="redisClient" class="com.cathy.demo.redis.RedisClientImpl"/>
<bean id="redisExecuteTemplate" class="com.cathy.demo.redis.RedisExecuteTemplate"/>
</beans>

**
* 序列化工具
* @author zhangwei_david
* @version $Id: SerializationUtil.java, v 0.1 2014年12月31日 下午5:41:35 zhangwei_david Exp $
*/
public class SerializationUtil {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
private static Objenesis                objenesis    = new ObjenesisStd(true);
private 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[] serializer(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 ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
/**
* 反序列化
*
* @param data
* @param clazz
* @return
*/
public static <T> T deserializer(byte[] data, Class<T> clazz) {
try {
T obj = objenesis.newInstance(clazz);
Schema<T> schema = getSchema(clazz);
ProtostuffIOUtil.mergeFrom(data, obj, schema);
return obj;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}


/**
*
* @author zhangwei_david
* @version $Id: RedisTemplate.java, v 0.1 2015年6月6日 下午6:21:26 zhangwei_david Exp $
*/
@Component
public class RedisExecuteTemplate {
@Autowired
private ShardedJedisPool shardedJedisPool;
public ShardedJedis getRedisClient() {
try {
ShardedJedis shardJedis = shardedJedisPool.getResource();
return shardJedis;
} catch (Exception e) {
}
return null;
}
@SuppressWarnings("deprecation")
public void returnResource(ShardedJedis shardedJedis) {
shardedJedisPool.returnResource(shardedJedis);
}
public Object excute(ExecuteCallback executeCallback) {
ShardedJedis shardedJedis = getRedisClient();
if (shardedJedis == null) {
return null;
}
try {
// 通过回调方法执行具体执行
return executeCallback.command(shardedJedis);
} catch (Exception e) {
} finally {
// 释放资源
returnResource(shardedJedis);
}
return null;
}
/**
*
*
* @author zhangwei_david
* @version $Id: RedisExecuteTemplate.java, v 0.1 2015年6月6日 下午7:45:58 zhangwei_david Exp $
*/
public interface ExecuteCallback {
public Object command(ShardedJedis shardedJedis);
}
}


/**
*
* @author zhangwei_david
* @version $Id: RedisClient.java, v 0.1 2015年6月6日 下午7:38:43 zhangwei_david Exp $
*/
public interface RedisClient {
/**
*
*
* @param key
* @param obj
* @param expire
* @return
*/
public boolean putObjectWithExpire(String key, Object obj, long expire);
/**
*
*  从Redis缓存中获取key指定的对象
* @param key
* @param clazz
* @return
*/
public Object getObjectByKey(String key, Class<?> clazz);
}


/**
*
* @author zhangwei_david
* @version $Id: RedisClient.java, v 0.1 2015年6月6日 下午6:35:25 zhangwei_david Exp $
*/
@Component("redisClient")
public class RedisClientImpl implements RedisClient {
@Autowired
private RedisExecuteTemplate redisExecuteTemplate;
/**
*
* @see com.cathy.demo.redis.RedisClient#putObjectWithExpire(java.lang.String, java.lang.Object, long)
*/
public boolean putObjectWithExpire(final String key, final Object obj, final long expireTime) {
String result = (String) redisExecuteTemplate.excute(new ExecuteCallback() {
byte[] objSeria = SerializationUtil.serializer(obj);
public Object command(ShardedJedis shardedJedis) {
return shardedJedis.set(key, new String(objSeria), "nx", "ex", expireTime);
}
});
return "OK".equals(result);
}
/**
*
* @see com.cathy.demo.redis.RedisClient#getObjectByKey(java.lang.String, java.lang.Class)
*/
public Object getObjectByKey(final String key, final Class<?> clazz) {
return redisExecuteTemplate.excute(new ExecuteCallback() {
public Object command(ShardedJedis shardedJedis) {
String str = shardedJedis.get(key);
return SerializationUtil.deserializer(str.getBytes(), clazz);
}
});
}
}


/**
*
* @author zhangwei_david
* @version $Id: RedisClientTest.java, v 0.1 2015年6月6日 下午6:38:24 zhangwei_david Exp $
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:META-INF/spring/jedis-beans.xml")
public class RedisClientTest {
@Autowired
private RedisClientImpl redisClient;
@Test
public void testSet() {
redisClient.putObjectWithExpire("my1.person.test", new Person(), 100);
Person person = (Person) redisClient.getObjectByKey("my1.person.test", Person.class);
System.out.println(person.getName());
}
}


log4j:WARN custom level class [# 输出DEBUG级别以上的日志] not found.
2015-06-06 19:43:09  [ main:0 ] - [ INFO ]  @TestExecutionListeners is not present for class [class com.cathy.demo.redis.RedisClientTest]: using defaults.
2015-06-06 19:43:09  [ main:145 ] - [ INFO ]  Loading XML bean definitions from URL [file:/H:/Alipay.com/workspace4alipay/demo/target/classes/META-INF/spring/jedis-beans.xml]
2015-06-06 19:43:09  [ main:314 ] - [ INFO ]  JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
2015-06-06 19:43:09  [ main:333 ] - [ INFO ]  Refreshing org.springframework.context.support.GenericApplicationContext@43840: startup date [Sat Jun 06 19:43:09 CST 2015]; root of context hierarchy
2015-06-06 19:43:09  [ main:489 ] - [ INFO ]  Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@525845: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,shardedJedisPool,jedisPoolConfig,redisClient,redisExecuteTemplate,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Test
2015-06-06 19:43:09  [ Thread-3:742 ] - [ INFO ]  Closing org.springframework.context.support.GenericApplicationContext@43840: startup date [Sat Jun 06 19:43:09 CST 2015]; root of context hierarchy
2015-06-06 19:43:09  [ Thread-3:743 ] - [ INFO ]  Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@525845: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,shardedJedisPool,jedisPoolConfig,redisClient,redisExecuteTemplate,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-317016-1-1.html 上篇帖子: redis expires key不会自动删除的问题 下篇帖子: redis五种数据类型对象的实现及场景分析
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表