1、首先我们的pom中添加有关redis和jedis的依赖,其中jedis用于连接redis。
<!-- 配置redis缓存 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.1.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- 配置redis结束 -->
注意:引入的redis和jedis版本必须对应,否则在运行的时候,会抛出Error creating bean with name 'redisTemplate' 的错误,如果对版本没有特殊要求,请按照上面引入的版本进行测试。如果更换版本的话,请确认好对应版本。
2、设置redis.properties的配置文件
# Redis服务器地址
redis.host=ip
# Redis服务器连接端口
redis.port=6379
# Redis服务器连接密码(默认为空)
redis.pass=password
# 连接池中的最大空闲连接
redis.maxIdle=300
# 连接池最大连接数(使用负值表示没有限制)
redis.maxActive=600
# 连接池最大阻塞等待时间(使用负值表示没有限制)
redis.maxWait=1000
redis.testOnBorrow=true
3、配置redis-context.xml,用于解析redis的配置文件
<?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:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<!-- 不同版本的jedis,加载参数的名称不同 -->
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}"
p:port="${redis.port}"
p:password="${redis.pass}"
p:pool-config-ref="poolConfig"/>
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">