Redis学习之与Spring整合开发

来源:互联网 发布:可视化编程的最大优点 编辑:程序博客网 时间:2024/06/03 02:26

在网上看了Redis整合Spring的文章,都是加入了spring配置的代码,很冗余,让读者不易理解。

本篇就不贴出配置Spring的代码,直接给出与Redis相关配置及代码,建立在Spring项目已经配置好的基础上。


第一步:引入jar包

需要引入和Redis 相关的两个jar包,一个是spring-data-redis.jar,另一个是jedis.jar。

具体的jar包在maven中心库里面都能找到。

maven项目pom.xml的配置:

<!-- redis缓存 --><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>1.3.4.RELEASE</version></dependency><dependency>    <groupId>redis.clients</groupId>    <artifactId>jedis</artifactId>    <version>2.5.2</version></dependency>

第二步:新建RedisCache.class类,自定义Cache。

package com.qcjy.common.cache;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import org.apache.log4j.Logger;import org.springframework.cache.Cache;import org.springframework.cache.support.SimpleValueWrapper;import org.springframework.dao.DataAccessException;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.RedisTemplate;/** * 自定义cache,可以定义一个cache名称和一个缓存失效时间。时间到期会自动更新。在xml中配置。 * <功能详细描述> *  * @author  lcma * @version  [版本号, 2016年9月12日] * @see  [相关类/方法] * @since  [产品/模块版本] */public class RedisCache implements Cache {    /**     * LOG日志     */    private static final Logger LOGGER = Logger.getLogger(RedisCache.class);        private RedisTemplate<String, Object> redisTemplate;        /**     * 缓存名称     */    private String name;        /**     * 缓存失效时间,时间到了会自动更新     */    private long liveTime = 0;        public RedisTemplate<String, Object> getRedisTemplate() {        return redisTemplate;    }        public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {        this.redisTemplate = redisTemplate;    }        public void setName(String name) {        this.name = name;    }        @Override    public String getName() {        return this.name;    }        @Override    public Object getNativeCache() {        return this.redisTemplate;    }        /**     * 获取     */    @Override    public ValueWrapper get(Object key) {        final String keyf = (String)key;        Object object = null;        object = redisTemplate.execute(new RedisCallback<Object>() {            public Object doInRedis(RedisConnection connection)                throws DataAccessException {                                byte[] key = keyf.getBytes();                byte[] value = connection.get(key);                if (value == null) {                    return null;                }                return toObject(value);                            }        });        return object != null ? new SimpleValueWrapper(object) : null;    }        /**     * 新建     */    @Override    public void put(Object key, Object value) {        final String keyf = (String)key;        final Object valuef = value;                redisTemplate.execute(new RedisCallback<Long>() {            public Long doInRedis(RedisConnection connection)                throws DataAccessException {                byte[] keyb = keyf.getBytes();                byte[] valueb = toByteArray(valuef);                connection.set(keyb, valueb);                if (getLiveTime() > 0) {                    connection.expire(keyb, getLiveTime());                }                return 1L;            }        });    }        /**     * 删除     */    @Override    public void clear() {        redisTemplate.execute(new RedisCallback<String>() {            public String doInRedis(RedisConnection connection)                throws DataAccessException {                connection.flushDb();                return "ok";            }        });    }        /**      * 描述 : <Object转byte[]>. <br>      * <p>      * <使用方法说明>      * </p>      *       * @param obj      * @return      */    private byte[] toByteArray(Object obj) {        byte[] bytes = null;        ByteArrayOutputStream bos = new ByteArrayOutputStream();        try {            ObjectOutputStream oos = new ObjectOutputStream(bos);            oos.writeObject(obj);            oos.flush();            bytes = bos.toByteArray();            oos.close();            bos.close();        } catch (IOException ex) {            LOGGER.error(ex.getMessage(),ex);        }        return bytes;    }        /**      * 描述 : <byte[]转Object>. <br>      * <p>      * <使用方法说明>      * </p>      *       * @param bytes      * @return      */    private Object toObject(byte[] bytes) {        Object obj = null;        try {            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);            ObjectInputStream ois = new ObjectInputStream(bis);            obj = ois.readObject();            ois.close();            bis.close();        } catch (IOException ex) {            LOGGER.error(ex.getMessage(),ex);        } catch (ClassNotFoundException ex) {            LOGGER.error(ex.getMessage(),ex);        }        return obj;    }        @Override    public void evict(Object key) {        final String keyf = (String)key;        redisTemplate.execute(new RedisCallback<Long>() {            public Long doInRedis(RedisConnection connection)                throws DataAccessException {                return connection.del(keyf.getBytes());            }        });    }        @Override    public <T> T get(Object key, Class<T> type) {                return null;    }        @Override    public ValueWrapper putIfAbsent(Object key, Object value) {        return null;    }        public long getLiveTime() {        return liveTime;    }        public void setLiveTime(long liveTime) {        this.liveTime = liveTime;    }    }

第三步:新建spring-redis.xml,配置Redis相关信息。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:cache="http://www.springframework.org/schema/cache" xmlns:c="http://www.springframework.org/schema/c"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">            <!-- 开启缓存注解 --><cache:annotation-driven cache-manager="cacheManager" /><!-- jedis客户端连接工厂 --><bean id="jedisConnectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"p:host-name="127.0.0.1"  p:port="6379" p:password="123456" /><!-- redisTemplate模板 --><bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"p:connection-factory-ref="jedisConnectionFactory" /><!-- spring自己的管理器,这里定义了三个缓存位置名称 ,既注解中的value --><bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"><property name="caches"><set><bean class="com.qcjy.common.cache.RedisCache">  <!-- 短期缓存 1个小时--><property name="redisTemplate" ref="redisTemplate" /><property name="name" value="shortTimeCache" /><property name="liveTime" value="3600" /></bean><bean class="com.qcjy.common.cache.RedisCache"> <!-- 长期缓存 4个小时--><property name="redisTemplate" ref="redisTemplate" /><property name="name" value="longTimeCache" /><property name="liveTime" value="14400" /></bean><bean class="com.qcjy.common.cache.RedisCache"> <!-- 永久缓存 --><property name="redisTemplate" ref="redisTemplate" /><property name="name" value="nerverTimeCache" /><property name="liveTime" value="0" /></bean></set></property></bean></beans>

com.qcjy.common.cache.RedisCache 是我的项目自定义cache的类路径,可根据自己项目类路径变换。


第四步:在spring配置文件中引入导入上面的redis缓存配置

<!-- 集成Redis缓存框架 --><import resource="spring-redis.xml" />

第五步:在方法上面添加注解

/** * getProject:根据id获取数据. <br/> * @author lcma * @param id * @return * @since JDK 1.7 */@Override@Cacheable(value = "shortTimeCache", key = "'getProject'+#id")public Project getProject(String id) {return projectDao.getById(id);}

缓存注解有三种,分别是:@CachePut,@Cacheable,@CacheEvict。它们之间的区别下篇再做详解。

到此,Redis与Spring整合成功啦,哈哈。


2 0
原创粉丝点击