Spring Data Redis 使用
2016-07-30 12:01
330 查看
Spring Data Redis使用
Spring Data Redis 使用键值对存储数据方式及提供了高度抽象的模板对Redis接收/发送消息进行管理,和其他Spring Data系列的操作差不多。由于Redis是基于键值对存储数据,Spring Data Redis依赖于Spring Data Common和Spring Data KeyValue。以下内容基于今年发布的1.7.2版本的SPring Data Redis。Spring Data Redis 配置
首先在idea中创建maven项目,不选择模板,如下图配置pom.xml<?xml version="1.0" encoding="UTF-8"?> <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.0</modelVersion> <groupId>com.luzhu</groupId> <artifactId>redis2</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- Junit 测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> </dependency> <!-- Redis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency> <!-- Spring Data Redis --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.2.RELEASE</version> </dependency> </dependencies> </project>
选择项目右键 make moudle,自动处理依赖。
基于Template方式
首先在resouce下右键新建xml,选择是spring Config,名字为spring-redis.xml,配置如下:<?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: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 "> <!--导入redis property配置信息--> <context:property-placeholder location="classpath:redis.properties"></context:property-placeholder> <!--配置 redis 连接池信息--> <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> <!-- Redis Template --> <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; } }
BaseRedisDao
public class BaseRedisDao<K,V> { @Resource protected RedisTemplate<K,V> redisTemplate; public RedisTemplate<K, V> getRedisTemplate() { return redisTemplate; } public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) { this.redisTemplate = redisTemplate; } protected RedisSerializer<String> getRedisSerializer(){ return redisTemplate.getStringSerializer(); } }
UserDao
public interface UserDao { public boolean addUser(User user); }
UserDaoImpl
@Component public class UserDaoImpl extends BaseRedisDao<String,User> implements UserDao{ public boolean addUser(final User user) { boolean result=redisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer=getRedisSerializer(); byte[] key=serializer.serialize(user.getId()); byte[] name=serializer.serialize(user.getName()); return connection.setNX(key,name); } }); return result; } }
测试类 UserDaoImplTest
@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的方式
基于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<Work> 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/。相关文章推荐
- 在spring data jpa中使用redis的通用list及entity存储方法
- spring-data-redis 使用过程中需要注意的一点
- 使用spring-data-redis开发redis应用
- 在Spring-data-Redis中如何使用特定的库?
- Spring-data-redis配置及使用示例
- 使用Spring Data +Redis实现缓存
- spring-data-redis 使用
- jedis,spring-redis-data 整合使用,版本问题异常以及解决。
- spring-data-redis 使用
- spring-data-redis 使用
- Spring+redis,spring-data-redis使用
- 使用spring-data-redis操作Redis的Sentinel
- spring-data-redis使用RedisTemplate模板存储时键值与预设不一致的解决方法
- spring-data-redis的使用优化
- 使用spring-data-redis操作redis
- 【Redis基础】SSH 中Spring-data-redis使用体验
- spring data redis 集群(sentinel实现)和simple spring memcached分布式初使用
- 6、redis之使用spring-data-redis的Template
- SSH 中Spring-data-redis使用(使用baseService)
- 使用Spring Data Redis实现缓存遇到的一些问题