spring中整合redis

来源:互联网 发布:淘宝客 微信 编辑:程序博客网 时间:2024/06/02 06:15

使用maven

1.在pom.xml中加入依赖

[html] view plain copy<repository>     <id>spring-milestone</id>     <name>Spring Maven MILESTONE Repository</name>     <url>http://maven.springframework.org/milestone</url>    </repository>    <dependency>     <groupId>org.springframework.data</groupId>     <artifactId>spring-data-redis</artifactId>     <version>1.0.0.RC1</version>    </dependency>  

如果没有使用maven,那直接下载jar包http://s3.amazonaws.com/dist.springframework.org/release/DATAKV/spring-data-redis-1.0.0.RELEASE.zip

2.spring配置文件里添加

<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">            <property name="hostName" value="localhost"/>            <property name="port" value="6636"/>    </bean>    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">            <property name="connectionFactory" ref="jedisConnectionFactory"/>    </bean>   

那就可以直接用redisTemplate,redisTemplate和HibernateTemplate很相似。

3.java代码

@Service    public class RedisService {        @Resource        private RedisTemplate<Serializable, Serializable> template;     /**        * 向redis里面添加key-value格式的数据        *        * @param key   key        * @param value value        */        public void set(final Serializable key, final Serializable value) {            template.execute(new RedisCallback<Object>() {                @Override                public Object doInRedis(RedisConnection connection) throws DataAccessException {                    byte[] key_ = RedisUtil.getBytesFromObject(key);                    byte[] value_ = RedisUtil.getBytesFromObject(value);                    connection.set(key_, value_);                    return true;                }            });        }     /**        * 根据key从redis里面取出value        *        * @param key   key        */     public Serializable get(final Serializable key) {            return template.execute(new RedisCallback<Serializable>() {                @Override                public Serializable doInRedis(RedisConnection connection) throws DataAccessException {                    byte[] keyBytes = RedisUtil.getBytesFromObject(key);                    byte[] bytes = connection.get(keyBytes);                    return (Serializable) RedisUtil.getObjectFromBytes(bytes);                }            });        }    }    

看了一点JedisConnectionFactory,之际上它只是对Jedis做了下简单了封装,再加上自己的连接池实现。

0 0
原创粉丝点击