`
zhangwei_david
  • 浏览: 469492 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Spring+Jedis+Redis自定义模板实现缓存Object对象

 
阅读更多

 

     在实际使用缓存的过程中,我们希望放入缓存的并不是一个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
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics