第一步:导入jar
<!-- redis start-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- redis Spring 基于注解配置 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<!-- redis end-->
第二步:编写redis属性文件redis.properties
redis.host = 127.0.0.1
redis.port = 6379
redis.pwd=
redis.maxTotal = 100
redis.maxIdle = 20
redis.maxWaitMillis = 10000
redis.testOnBorrow = true
redis.testOnReturn = true
redis.dbIndex = 1
第三步:编写spring配置文件spring-redis.xml
<!--设置jedisPool链接池的配置-->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxTotal}"/>
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
<property name="testOnReturn" value="${redis.testOnReturn}"/>
</bean>
<!--redis链接密码-->
<bean id="redisPassword" class="org.springframework.data.redis.connection.RedisPassword">
<constructor-arg name="thePassword" value="${redis.pwd}"></constructor-arg>
</bean>
<!--spring-data-redis2.0以上的配置-->
<bean id="redisStandaloneConfiguration" class="org.springframework.data.redis.connection.RedisStandaloneConfiguration">
<property name="hostName" value="${redis.host}"/>
<property name="port" value="${redis.port}"/>
<property name="password" ref="redisPassword" />
<property name="database" value="${redis.dbIndex}"/>
</bean>
<!--配置jedis链接工厂 spring-data-redis2.0中 建议改为构造器传入一个RedisStandaloneConfiguration-->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!--spring-data-redis2.0以上建议获取的方式-->
<constructor-arg name="standaloneConfig" ref="redisStandaloneConfiguration"/>
</bean>
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"/>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<!--开启事务 -->
<property name="enableTransactionSupport" value="true"></property>
</bean>
第四步:在主配置文件applicationContext.xml中引入spring-redis.xml配置
<!--导入redis配置-->
<import resource="classpath:spring-redis.xml"/>