最近在修改之前旧项目的时候,将spring-data-redis的版本升级到了2.X以上,查看了官方的文档之后,发现新版本有一些新特性和新的使用方法,这里记录整理一下,并附上自己在使用的时候遇到的一点坑。 spring-data-redis最新版官方文档
spring-redis.xml配置(spring整合spring-data-redis)
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Redis连接池的配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 控制一个pool可以分配多少个jedis实例 -->
<property name="maxTotal" value="${redis.pool.maxActive}" />
<!-- 连接池中最多可空闲链接个数,这里取值20,表示即使没有用数据库链接依然保持20个空闲链接 -->
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<!-- 最大等待时间,当没有可用连接时,连接池等待链接被归还的最大时间ms,超过时间就抛出异常 -->
<property name="maxWaitMillis" value="${redis.pool.maxWait}" />
<!-- 在获取连接的时候检查链接的有效性 -->
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
</bean>
<!-- 配置redis连接密码 -->
<bean id="redisPassword" class="org.springframework.data.redis.connection.RedisPassword">
<constructor-arg name="thePassword" value="${redis.auth}"></constructor-arg>
</bean>
<!-- redis单机配置,地址等在这配置 2.0以上的新特性 -->
<bean id="redisStandaloneConfiguration" class="org.springframework.data.redis.connection.RedisStandaloneConfiguration">
<property name="hostName" value="${redis.hostname}"/>
<property name="port" value="${redis.port}"/>
<property name="password" ref="redisPassword"/>
<property name="database" value="${redis.database}"/>
</bean>
<!--配置jedis链接工厂 spring-data-redis2.0中
建议改为构造器传入一个RedisStandaloneConfiguration 单机
RedisSentinelConfiguration 主从复制
RedisClusterConfiguration 集群-->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<constructor-arg name="standaloneConfig" ref="redisStandaloneConfiguration">