如果要在 Spring 中集成 Redis,可以直接装载 Jedis 的 JedisPoolFactory ,需要自己封装 RedisRemplate,Spring 子项目 spring-data-reids 对 Redis 客户端提供高度的封装,可以很方便地调用 RedisTemplate;
Spring Data Redis 项目主页:
Spring Data Redis 2.0.3 技术文档
以下以一个简单的 Web 程序中经典的 CRUD 作为示例,完整示例代码地址: https://gitee.com/assad/spring-data-redis_sample
构建依赖脚本 build.gradle
...
// 依赖部分
dependencies {
//redis-jedis 依赖
compile 'redis.clients:jedis:2.9.0'
//spring-data-redis 依赖
compile 'org.springframework.data:spring-data-redis:2.0.3.RELEASE'
//spring core 依赖
compile "org.springframework:spring-beans:4.3.14.RELEASE"
compile "org.springframework:spring-core:4.3.14.RELEASE"
compile "org.springframework:spring-context:4.3.14.RELEASE"
//spring test 依赖
compile "org.springframework:spring-test:4.3.14.RELEASE"
testCompile "junit:junit:4.12"
//log4j 依赖
compile 'org.slf4j:slf4j-nop:1.7.25'
compile "org.apache.logging.log4j:log4j-core:2.9.0"
compile "org.apache.logging.log4j:log4j-api:2.9.0"
}
...
spring 上下文配置文件 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<!--扫描bean-->
<context:component-scan base-package="site.assad.service" />
<context:component-scan base-package="site.assad.dao" />
<!--配置 JedisPoolConfig -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"
p:maxIdle="300"
p:maxTotal="1000"
p:maxWaitMillis="1000"
p:testOnBorrow="true"
p:testOnReturn="true"/>
<!--配置 Jedis 连接对象-->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
destroy-method="destroy"
p:host-name="127.0.0.1"
p:port="6379"
p:password="assad"
p:usePool="true"
p:poolConfig-ref="jedisPoolConfig"/>
<!--装配 RedisTemplate -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connectionFactory-ref="jedisConnectionFactory" />
</beans>
大概的业务流程如下:service 层的 UserService 通过 dao 层的 UserDao 层对 User 对象进行 CRUD 操作,在这个 CRUD 操作的基上进行 User 对象的缓存操作;
User 对象, site.assad.domian.User
package site.assad.domain;
public class User implements Serializable{
private static final long serialVersionUID = 23333L;
private int id;
private String name;
private String password;
private String icon;
// getter,setter,toString,constructor
}