【环境参数】

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环境搭建具体步骤的更多相关文章

  1. 【原】Spring整合Redis(第一篇)—SDR简述

    1.SDR说明 Spring Data Redis(SDR),是SpringFramework提供的一套简化访问Redis的API,是对Jedis的又一层封装. SDR集成了Jedis,JRedis, ...

  2. Spring整合Redis&JSON序列化&Spring/Web项目部署相关

    几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...

  3. 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 ...

  4. 网站性能优化小结和spring整合redis

    现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...

  5. spring整合redis之hello

    1.pom.xml文件 <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.spri ...

  6. Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object

    我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!

  7. Spring整合redis实现key过期事件监听

    打开redis服务的配置文件   添加notify-keyspace-events Ex  如果是注释了,就取消注释 这个是在以下基础上进行添加的 Spring整合redis:https://www. ...

  8. C语言编程入门之--第二章编译环境搭建

    第二章 编译环境搭建 导读:C语言程序如何工作,首先需要编译链接成可执行文件,然后就可以运行在不同的环境中,这个“环境”的意思就是比如说,电脑,手机,路由器,蓝牙音箱等等智能设备中,其中编译器启到了关 ...

  9. Redis 快速集群环境搭建

    环境 Linux :centos 7 redis:redis-5.0.9 Redis 集群环境搭建步骤 早期 redis 版本集群环境搭建需要安装 ruby 运行环境,搭建步骤比较繁琐: redis ...

随机推荐

  1. [整理].net中的延迟初始化器

    LazyInitializer类 private void EnsureInitialized() { LazyInitializer.EnsureInitialized(ref _initializ ...

  2. phpStorm 8.0.3 设置

    phpstorm 8 license key Learn Programming===== LICENSE BEGIN =====63758-1204201000000Ryqh0NCC73lpRm!X ...

  3. the error about “no such file or directory”

    CHENYILONG Blog the error about "no such file or directory" when you get the question like ...

  4. shell 判断路径

    判断路径 ];then echo "找到了123" if [ -d /root/Desktop/text ] then echo "找到了text" else ...

  5. 解决Winsock2.h和afxsock.h定义冲突的办法

    如果我们在工程中使用了afxsock.h,但在其它的地方又加了些 使用winsock2.h,哈哈,VC会告诉你一大堆错误,大意就是有定义重复,该怎么解决? 由于MFC的SOCKET类使用的是Winso ...

  6. 第11月第18天 RACSequence

    1. RACSequence的内部存储结构就像一个单链表,有两个指针head和tail,head指针指向了当前链表的第一个元素,tail指向head指针下一个元素:根据RACSequence是否还有内 ...

  7. 无法执行该操作,因为链接服务器 "xxxxx" 的 OLE DB 访问接口 "SQLNCLI" 无法启动分布式事务

    在存储过程中使用事务,并且使用链接服务器时,报类似下面的错误 链接服务器"****"的 OLE DB 访问接口 "SQLNCLI10" 返回了消息 " ...

  8. Java实现去火柴游戏

    package com.gh.p10; /** * Created by Lenovo on 2014/12/10. */ import java.util.Random; import java.u ...

  9. j2ee组件简介

  10. springboot创建一个可执行的jar

    让我们通过创建一个完全自包含的可执行jar文件来结束我们的示例,该jar文件可以在生产环境运行.可执行jars(有时候被成为胖jars "fat jars")是包含你的编译后的类和 ...