Spring Data Redis 使用键值对存储数据方式及提供了高度抽象的模板对Redis接收/发送消息进行管理,和其他Spring Data系列的操作差不多。由于Redis是基于键值对存储数据,Spring Data Redis依赖于Spring Data Common和Spring Data KeyValue。以下内容基于今年发布的1.7.2版本的SPring Data Redis。
首先在idea中创建maven项目,不选择模板,如下图配置pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.luzhugroupId>
<artifactId>redis2artifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
dependency>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>2.7.3version>
dependency>
<dependency>
<groupId>org.springframework.datagroupId>
<artifactId>spring-data-redisartifactId>
<version>1.7.2.RELEASEversion>
dependency>
dependencies>
project>
选择项目右键 make moudle,自动处理依赖。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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
">
<context:property-placeholder location="classpath:redis.properties">context:property-placeholder>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}">property>
<property name="maxWaitMillis" value="${redis.maxWaitMillis}">property>
<property name="testOnBorrow" value="${redis.testOnBorrow}">property>
bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:hostName="${redis.host}"
p:port="${redis.port}"
p:password="${redis.password}"
p:poolConfig-ref="jedisPoolConfig">
bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory">property>
bean>
<context:component-scan base-package="com.luzhu.*">context:component-scan>
beans>
redis 连接配置Property如下:
redis.maxIdle=10
redis.maxWaitMillis=6000
redis.testOnBorrow=true
redis.host=127.0.0.1
redis.port=6379
redis.password=root
public class User {
private String id;
private String name;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class BaseRedisDao<K,V> {
@Resource
protected RedisTemplate redisTemplate;
public RedisTemplate getRedisTemplate() {
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
protected RedisSerializer getRedisSerializer(){
return redisTemplate.getStringSerializer();
}
}
public interface UserDao {
public boolean addUser(User user);
}
@Component
public class UserDaoImpl extends BaseRedisDao<String,User> implements UserDao{
public boolean addUser(final User user) {
boolean result=redisTemplate.execute(new RedisCallback() {
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer serializer=getRedisSerializer();
byte[] key=serializer.serialize(user.getId());
byte[] name=serializer.serialize(user.getName());
return connection.setNX(key,name);
}
});
return result;
}
}
@ContextConfiguration(locations = {"classpath:spring-redis.xml"})
public class UserDaoTest extends AbstractJUnit4SpringContextTests{
@Autowired
private UserDao userDao;
@Test
public void testAddUser(){
User user=new User();
user.setId("usedffr341");
user.setName("userName34");
user.setPassword("zxc");
boolean result=userDao.addUser(user);
Assert.assertTrue(result);
}
}
基于Template方式,基本上是调用redisTemplate或是RedisConnection的方法,
RedisConnection提供了对Redis的大部分操作。这种方式操作Redis比较方便,但有时比较麻烦,下面的方式基于repository,这种方式和Spring Data JPA/MongoDB方式差不多,用起来基本方便。
基于Repository的方式目前只提供Class配置的方式(官网上没找到基于xml配置),所以一开始根据新建一个AppConfig类,在类上新增注解@EnableRedisRepositories,设置repository包所在,开启RedisRepository方式,在类中配置了connectionFactory和redisTemplate。如下:
@Configuration
@EnableRedisRepositories(basePackages = {"com.luzhu.*"},redisTemplateRef="redisTemplate")
public class AppConfig {
@Bean
public RedisConnectionFactory connectionFactory(){
return new JedisConnectionFactory();
}
@Bean()
public RedisTemplate,?> redisTemplate(){
RedisTemplate<byte[],byte[]> template=new RedisTemplate<byte[], byte[]>();
template.setConnectionFactory(connectionFactory());
return template;
}
}
创建模型类,在模型类中添加@RedisHash注解,可以设置有效时间,在key上写@Id注解。
@RedisHash(value = "work")
public class Work {
@Id
private String id;
@Indexed
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
创建WorkDao 接口,让其继承spring data common 的CrudRepository接口,这个接口实现了基本的增删查改方法。
public interface WorkDao extends CrudRepository<Work,String> {
}
可以测试以下了,如下:
@ContextConfiguration(classes={AppConfig.class})
public class WorkDaoTest extends AbstractJUnit4SpringContextTests {
@Autowired
private WorkDao workDao;
@Test
public void test(){
Work work=new Work();
// work.setName("work_nfdfddfame");
// work.setId("dssdfdkfdkdfdfdffdk");
// workDao.save(work);
Iterable works=workDao.findAll();
for(Work tWork:works){
System.out.println(tWork.getId()+" "+tWork.getName());
}
}
}
基于Repository的方式目前只在高版本的Spring Data Redis才实现。
在俩种方式中,基于Template方式使用起来比较自由,实现的功能比较多,而Repository方式目前实现功能较少。具体使用文档可以参照http://docs.spring.io/spring-data/redis/docs/1.7.2.RELEASE/reference/html/。