Spring Data Redis简单搭建

来源:互联网 发布:矩阵音响 编辑:程序博客网 时间:2024/06/07 03:59

1.pom依赖

        <dependency>            <groupId>redis.clients</groupId>            <artifactId>jedis</artifactId>            <version>2.9.0</version>        </dependency>        <dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-redis</artifactId>            <version>1.8.5.RELEASE</version>        </dependency>

2.配置文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    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/context http://www.springframework.org/schema/context/spring-context.xsd">    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">        <property name="maxTotal" value="10"></property><!-- 控制一个pool可分配多少个jedis实例 -->        <property name="maxIdle" value="10"></property><!-- 最大能够保持idel状态的对象数 -->        <property name="minIdle" value="2"></property><!-- 最少能够保持idel状态的对象数 -->        <property name="maxWaitMillis" value="15000"></property><!-- 表示当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException -->        <property name="minEvictableIdleTimeMillis" value="300000"></property><!-- 空闲连接多长时间后会被收回, 单位是毫秒 -->        <property name="numTestsPerEvictionRun" value="3"></property>        <property name="timeBetweenEvictionRunsMillis" value="60000"></property><!-- 多长时间检查一次连接池中空闲的连接 -->        <property name="testOnBorrow" value="true"></property><!-- 当调用borrow Object方法时,是否进行有效性检查 -->        <property name="testOnReturn" value="true"></property><!-- 当调用return Object方法时,是否进行有效性检查 -->        <property name="testWhileIdle" value="true"></property>    </bean>    <bean id="jedisConnectionFactory"        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"        destroy-method="destroy">        <property name="hostName" value="127.0.0.1" />        <property name="port" value="6379" />        <property name="timeout" value="15000" />        <property name="database" value="0" />        <property name="password" value="" />        <property name="usePool" value="true" />        <property name="poolConfig" ref="jedisPoolConfig" />    </bean>    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"        p:connection-factory-ref="jedisConnectionFactory">        <property name="keySerializer">            <bean                class="org.springframework.data.redis.serializer.StringRedisSerializer" />        </property>        <property name="hashKeySerializer">            <bean                class="org.springframework.data.redis.serializer.StringRedisSerializer" />        </property>        <property name="valueSerializer">            <bean                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />        </property>        <property name="hashValueSerializer">            <bean                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />        </property>    </bean>    <!-- 对string操作的封装 -->    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"        p:connection-factory-ref="jedisConnectionFactory" />    <!-- 存储对象序列化 -->    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">        <property name="connectionFactory" ref="jedisConnectionFactory" />    </bean></beans>  

3.创建value值是字符串的接口service

package com.spring.group.data.redis.service;public interface RedisStringService {    public void set(String key, String value);    public String get(String key);    public void rPushList(String key, String value);    public String lPopList(String key);    public void remove(String key);}

4.实现类

package com.spring.group.data.redis.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service;@Servicepublic class RedisStringServiceImpl<T> implements RedisStringService {    @Autowired    RedisTemplate<String, String> stringRedisTemplate;    @Override    public void set(String key, String value) {        stringRedisTemplate.opsForValue().set(key, value);    }    @Override    public String get(String key) {        return stringRedisTemplate.opsForValue().get(key);    }    @Override    public void rPushList(String key, String value) {        // TODO Auto-generated method stub    }    @Override    public String lPopList(String key) {        // TODO Auto-generated method stub        return null;    }    @Override    public void remove(String key) {        // TODO Auto-generated method stub    }}

创建序列化类

package com.spring.group.data.redis.dao;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.RedisSerializer;public class AbstractBaseRedisDao<K, V> {    @Autowired    protected RedisTemplate<K, V> redisTemplate;    public RedisTemplate<K, V> getRedisTemplate() {        return redisTemplate;    }    /**     * 获取 RedisSerializer     */    protected RedisSerializer<String> getRedisSerializer() {        return redisTemplate.getStringSerializer();    }}

创建接口

package com.spring.group.data.redis.service;public interface RedisService {    <T> void save(String key, T t);    <T> T get(String key);}

创建实现

package com.spring.group.data.redis.service;import java.io.Serializable;import org.springframework.beans.factory.annotation.Autowired;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;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Service;import com.spring.group.data.redis.dao.AbstractBaseRedisDao;@Servicepublic class RedisServiceImpl extends AbstractBaseRedisDao<String, Serializable> implements RedisService {    @Autowired    RedisTemplate<String, Serializable> redisTemplate;    @Override    public <T> void save(final String key, final T t) {        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {            @Override            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {                ValueOperations<String, T> valueOper = (ValueOperations<String, T>) redisTemplate.opsForValue();                valueOper.set(key, t);                return true;            }        }, false, true);    }    @Override    public <T> T get(final String key) {        T result = redisTemplate.execute(new RedisCallback<T>() {            public T doInRedis(RedisConnection connection) throws DataAccessException {                ValueOperations<String, Serializable> operations = redisTemplate.opsForValue();                T user = (T) operations.get(key);                return user;            }        });        return result;    }}

进行单元测试

package com.spring.group;import static org.junit.Assert.*;import java.util.Date;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.spring.group.data.mongo.domain.User;import com.spring.group.data.redis.service.RedisService;import com.spring.group.data.redis.service.RedisStringService;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({ "classpath:junit-config.xml", "classpath:META-INF/spring-redis.xml" })public class TestRedis {    @Autowired    RedisService redieService;    @Autowired    RedisStringService RedisStringService;    @Test    public void testSave() {        RedisStringService.set("name", "wzz");        String value = RedisStringService.get("name");        assertEquals(value, "wzz");        User user = new User();        user.setAge(12);        user.setName("aaa");        user.setBirthday(new Date());        redieService.save("user", user);        User user2 = redieService.get("user");        System.out.println(user2.toString());    }}
原创粉丝点击