【原】Spring整合Redis(第二篇)—SDR环境搭建具体步骤
【环境参数】
Spring版本:4.2.6.RELEASE
Spring-Data-Redis版本:1.7.2.RELEASE
Redis版本:redis-2.4.5-win32-win64
【简要说明】
搭建Spring与Reids的环境时,重点在于在Spring容器中配置RedisTemplate和ConnectionFactory,以及封装RedisTemplate组件。
【具体步骤】
0、配置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.0</modelVersion>
<groupId>com.zjrodger</groupId>
<artifactId>Spring-Redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <!-- 定义依赖的版本 -->
<properties>
<spring.version>4.2.6.RELEASE</spring.version>
</properties> <dependencies>
<!-- Spring Core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency> <!-- Spring Transaction -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency> <!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency> <!-- JUnit相关jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency> <!-- Spring-Date-Redis相关 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency> </dependencies> </project>
pom.xml
1、配置redis.properties属性文件
# 连接redis服务的ip
redis.host=127.0.0.1
# 连接redis服务的端口
redis.port=6379
# 连接redis服务的超时时间(单位:秒)
redis.timeout=10
# 连接redis服务的密码
#redis.password=zjrodger
# 连接redis服务的数据库
redis.database=2 # 最大连接数
redis.maxTotal=5000
# 最大空闲连接数
redis.maxIdle=100
# 最大等待时间:单位(毫秒)
redis.maxWait=10000
# 最小空闲连接数
redis.minIdle=10
# 在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的。
redis.testOnBorrow=true
# 在return给pool时,是否提前进行validate操作。
redis.testOnReturn=true
# 如果为true,表示有一个idle object evitor线程对idle object进行扫描,如果validate失败,此object会被从pool中drop掉;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义。
redis.testWhileIdle=false
redis.properties
2、在Spring容器中配置RedisTemplate和ConnectionFactory
在Spring容器中配置RedisTemplate和RedisConnectionFactory的实现类,即JedisConnectionFactory
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- Spring 扫包 -->
<context:component-scan base-package="com.zjrodger"/> <!-- 读取配置文件 -->
<context:property-placeholder location="classpath:properties/*.properties"/> <!-- jedis 配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" >
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean > <!-- redis服务器中心 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<property name="poolConfig" ref="poolConfig" />
<property name="port" value="${redis.port}" />
<property name="hostName" value="${redis.host}" />
<property name="timeout" value="${redis.timeout}" />
<property name="database" value="${redis.database}" />
<!-- <property name="password" value="${redis.password}"></property> -->
</bean > <!-- redisTemplate配置 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
</beans>
applicationContext-redis.xml
3、封装RedisTemplate组件。
@Component( value ="redisTemplateFactory" )
public class RedisTemplateFactory { @Autowired
private RedisTemplate<String, Object> redisTemplate; @SuppressWarnings("rawtypes")
public RedisTemplate getLocalRedisTemplate(){
redisTemplate.setKeySerializer(redisTemplate.getStringSerializer());
return this.redisTemplate;
}
}
RedisTemplateFactory
4、准备测试数据:实体类、Dao接口和其实现类。
(1)封装User实体类
 public class User implements Serializable {
     private String userId;
     private String username;
     private String password;
     ... 省略 setter()和getter()方法..
 }
User.java
(2)封装IUserDao接口
 public interface IUserDao {
     /** 新增 */
     boolean add(User user);  
     /** 批量新增 使用pipeline方式 */
     boolean add(List<User> list);     
     /**删除*/
     void delete(String key);  
     /**删除多个*/
     void delete(List<String> keys);  
     /**修改*/
     boolean update(User user) throws Exception;  
     /**通过key获取*/
     User get(String keyId);
     boolean opsForList(String key, User user);
     boolean getListValueByIndex(String key, int index);
 }
IUserDao.java
(3)实现IUserDao接口
@Component( value = "userDao")
public class UserDaoImpl implements IUserDao { @Autowired
public RedisTemplateFactory redisTemplateFactory; @SuppressWarnings("unchecked")
@Override
public boolean add(User user) {
RedisTemplate<String, Object> localRedisTemplate = redisTemplateFactory.getLocalRedisTemplate();
ValueOperations<String, Object> opsForValue = localRedisTemplate.opsForValue();
opsForValue.set(user.getUserId(), user);
return true;
} @SuppressWarnings("unchecked")
@Override
public boolean add(List<User> list) {
RedisTemplate<String, Object> localRedisTemplate = redisTemplateFactory.getLocalRedisTemplate();
ValueOperations<String, Object> opsForValue = localRedisTemplate.opsForValue();
for(User user: list){
opsForValue.set(user.getUserId(), user);
}
return true;
} @SuppressWarnings("unchecked")
@Override
public void delete(String key) {
RedisTemplate<String, Object> localRedisTemplate = redisTemplateFactory.getLocalRedisTemplate();
ValueOperations<String, Object> opsForValue = localRedisTemplate.opsForValue();
opsForValue.getOperations().delete(key);
} @SuppressWarnings("unused")
@Override
public void delete(List<String> keys) {
RedisTemplate<String, Object> localRedisTemplate = redisTemplateFactory.getLocalRedisTemplate();
ValueOperations<String, Object> opsForValue = localRedisTemplate.opsForValue();
RedisOperations<String, Object> operations = opsForValue.getOperations();
for(String key : keys){
operations.delete(key);
}
} @Override
public boolean update(User user) throws Exception {
if( null == user.getUserId()){
throw new Exception("该用户的Key不存在");
}
RedisTemplate<String, Object> localRedisTemplate = redisTemplateFactory.getLocalRedisTemplate();
ValueOperations<String, Object> opsForValue = localRedisTemplate.opsForValue();
opsForValue.set(user.getUserId(), user);
return true;
} @Override
public User get(String keyId) {
RedisTemplate<String, Object> localRedisTemplate = redisTemplateFactory.getLocalRedisTemplate();
ValueOperations<String, Object> opsForValue = localRedisTemplate.opsForValue();
return (User)opsForValue.get(keyId);
} @Override
public boolean opsForList(String key, User user) {
RedisTemplate<String, Object> localRedisTemplate = redisTemplateFactory.getLocalRedisTemplate();
ListOperations<String, Object> opsForList = localRedisTemplate.opsForList();
opsForList.rightPush(key, user);
return true;
} @Override
public boolean getListValueByIndex(String key, int index) {
RedisTemplate<String, Object> localRedisTemplate = redisTemplateFactory.getLocalRedisTemplate();
ListOperations<String, Object> opsForList = localRedisTemplate.opsForList();
User user = (User) opsForList.index(key, index);
System.out.println(user);
return true;
}
}
UserDaoImpl
5、测试:以OpsForXX()方式,对User的增删改查操作(推荐)。
此种方式是推荐的操作Redis的方式。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class SpringTestCase { @Autowired
private IUserDao userDao; private static final Integer COUNTER = 10; // 测试添加单个User
@Test
public void testAddUser(){
for(int i=1; i<=COUNTER; i++){
User user = new User("mykey000"+i, "zjroger000"+i, "password000"+i);
if( userDao.add(user) ){
System.out.println("用户zjrodger"+i+"添加成功。");
}else{
System.out.println("用户zjrodger"+i+"添加失败。");
}
}
} // 测试按照Key-Value方式添加User
@Test
public void testAddUserList(){
List<User> userList = new ArrayList<>();
for(int i=1; i<=COUNTER; i++){
User user = new User("mykey000"+i, "zjroger000"+i, "password000"+i);
userList.add(user);
}
if( userDao.add(userList) ){
System.out.println("用户列表添加成功。");
}else{
System.out.println("用户列表添加成功。");
}
} // 通过OpsForList方式添加User
@Test
public void testOpsForList(){
String myListKey = "key:myListKey01";
List<User> userList = new ArrayList<>();
for(int i=1; i<=COUNTER; i++){
User user = new User("myUserList0"+i, "myUserList0"+i, "myUserList0"+i);
userDao.opsForList(myListKey, user);
}
} @Test
public void testgetListValueByIndex(){
String myListKey = "key:myListKey01";
int index = 0;
userDao.getListValueByIndex(myListKey, index);
} // 测试删除User
@Test
public void testDelete(){
// 单个删除
// String key = "mykey0002";
// userDao.delete(key); // 多个删除
List<String> keys = new ArrayList<>();
keys.add("mykey0001");
keys.add("mykey0002");
keys.add("mykey0003");
userDao.delete(keys); } // 测试获取User
@Test
public void testGetUser(){
User user = userDao.get("mykey0001");
System.out.println(user.toString());
// 多条查询
// for(int i=1; i<=COUNTER; i++){
// User user = userDao.get("mykey0"+i);
// System.out.println(user.toString());
// }
} // 测试更新User
@Test
public void testUpdateUser(){
String mykey01 = "mykey0001";
User user = userDao.get(mykey01);
System.out.println("原来的用户:"+user.toString());
user.setUsername("ttttt"); try {
boolean result = userDao.update(user);
System.out.println("数据更新完毕。");
System.out.println(user.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
SpringRedisTestCase
6、测试:以RedisCallback()方式,对User的增删改查操作。
 public class UserDaoImpl implements IUserDao {
     @Autowired
     private RedisTemplateFactory redisTemplateFactory;    
     /**
      * 添加一个User对象
      */
     @SuppressWarnings("unchecked")
     @Override
     public boolean add(User user) {
         final RedisTemplate redisTemplate = redisTemplateFactory.getLocalRedisTemplate();
         boolean result = (boolean) redisTemplate.execute(new RedisCallback(){
             @SuppressWarnings("rawtypes")
             @Override
             public Boolean doInRedis(RedisConnection connection)
                     throws DataAccessException {
                 RedisSerializer stringSerializer = redisTemplate.getStringSerializer();
                 RedisSerializer<User> valueSerializer = redisTemplate.getValueSerializer();
                 byte[] key = stringSerializer.serialize(user.getUserId());
                 byte[] value = valueSerializer.serialize(user);
                 return connection.setNX(key, value);
             }
         });
         return result;
     }
     /** 添加一个User的List对象*/
     @SuppressWarnings("unchecked")
     @Override
     public boolean add(List<User> list) {
         final RedisTemplate redisTemplate = redisTemplateFactory.getLocalRedisTemplate();
         return (boolean) redisTemplate.execute(new RedisCallback(){
             @SuppressWarnings("rawtypes")
             @Override
             public Boolean doInRedis(RedisConnection connection)
                     throws DataAccessException {
                 RedisSerializer keySerializer = redisTemplate.getKeySerializer();
                 RedisSerializer<User> valueSerializer = redisTemplate.getValueSerializer();
                 for(User user : list){
                     byte[] key = keySerializer.serialize(user.getUserId());
                     byte[] value = valueSerializer.serialize(user);
                     connection.setNX(key, value);
                 }
                 return true;
             }
         },
         false,
         true);
     }
 }
UserDaoImpl
【原】Spring整合Redis(第二篇)—SDR环境搭建具体步骤的更多相关文章
- 【原】Spring整合Redis(第一篇)—SDR简述
		1.SDR说明 Spring Data Redis(SDR),是SpringFramework提供的一套简化访问Redis的API,是对Jedis的又一层封装. SDR集成了Jedis,JRedis, ... 
- Spring整合Redis&JSON序列化&Spring/Web项目部署相关
		几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ... 
- Redis的安装以及spring整合Redis时出现Could not get a resource from the pool
		Redis的下载与安装 在Linux上使用wget http://download.redis.io/releases/redis-5.0.0.tar.gz下载源码到指定位置 解压:tar -xvf ... 
- 网站性能优化小结和spring整合redis
		现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ... 
- spring整合redis之hello
		1.pom.xml文件 <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.spri ... 
- Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object
		我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了! 
- Spring整合redis实现key过期事件监听
		打开redis服务的配置文件 添加notify-keyspace-events Ex 如果是注释了,就取消注释 这个是在以下基础上进行添加的 Spring整合redis:https://www. ... 
- C语言编程入门之--第二章编译环境搭建
		第二章 编译环境搭建 导读:C语言程序如何工作,首先需要编译链接成可执行文件,然后就可以运行在不同的环境中,这个“环境”的意思就是比如说,电脑,手机,路由器,蓝牙音箱等等智能设备中,其中编译器启到了关 ... 
- Redis 快速集群环境搭建
		环境 Linux :centos 7 redis:redis-5.0.9 Redis 集群环境搭建步骤 早期 redis 版本集群环境搭建需要安装 ruby 运行环境,搭建步骤比较繁琐: redis ... 
随机推荐
- MySQL异步复制延迟解决
			http://www.ttlsa.com/mysql/mysql-5-7-enhanced-multi-thread-salve/ 
- ASP.net学习总结
			学习ASP.net又一次接触了B/S开发.下面先通过一张图对ASP.net有一个宏观结构的总结.之后将详细介绍ASP.net中的六大对象. 1.Request从客户端得到数据,包括基于表单的数据和通过 ... 
- 【BZOJ】2111: [ZJOI2010]Perm 排列计数   计数DP+排列组合+lucas
			[题目]BZOJ 2111 [题意]求有多少1~n的排列,满足\(A_i>A_{\frac{i}{2}}\),输出对p取模的结果.\(n \leq 10^6,p \leq 10^9\),p是素数 ... 
- 【转】[.Net] 确定当前网站的物理文件路径
			确定当前网站的物理文件路径 在应用程序中,您可能需要确定服务器上的文件或其他资源的路径.例如,如果应用程序以编程方式对文本文件进行读写操作,则必须为用于读取和写入的方法提供该文件的完整物理路径. 将物 ... 
- ARC 之内存转换
			CHENYILONG Blog ARC 之内存转换 技术博客http://www.cnblogs.com/ChenYilong/ 新浪微博http://weibo.com/luohanchenyilo ... 
- iOS 在viewDidLayoutSubviews自动布局crash问题
			1 viewDidLayoutSubviews改成viewWillLayoutSubviews在iOS7上就不会crash了2 viewDidLoad中还需要设置self.edgesForExtend ... 
- Palindrome Partitioning I & II
			Given a string s, partition s such that every substring of the partition is a palindrome. Return all ... 
- MySQL V5.6.37升级到V5.6.38
			简单!万事先备份 cp /usr/my.cnf /home/xx/ cp -r /var/lib/mysql/dbname /home/xx/ mysqldump -u root -ppasswd - ... 
- 解决阿里云安骑士漏洞警告:wordpress WPImageEditorImagick 指令注入漏洞
			解决:wordpress WPImageEditorImagick 指令注入漏洞 前些天在阿里云服务器上安装了wordpress,阿里云提示有wordpress WP_Image_Editor_Ima ... 
- kali linux2.0安装vega
			1.到官网下载安装包(选择版本:我这里以Linux64位为例) vega下载地址:https://subgraph.com/vega/download/ 2.解压到指定目录: unzip VegaBu ... 
