上篇博文简单介绍了如何安装Redis以及使用jedis操作redis缓存,以及连接池的使用,本博文介绍用spring来管理jedis连接池,这样获得更好的简洁性。
步骤:
1、在项目中引入相关的jar包
spring下载地址:http://pan.baidu.com/s/1c2zjlwG
2.新建一个Redis.properities的配置文件,方便参数管理
cache.redis.servers=127.0.0.1
cache.redis.port=6379
redis.pool.maxActive=300
redis.pool.maxIdle=200
redis.pool.maxWaitMillis=3000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
3 .配置spring.xml
<?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:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms-2.5.xsd" >
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:Redis.properties</value>
</list>
</property>
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxActive}"/>
<property name="maxIdle" value="${redis.pool.maxIdle}"/>
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"/>
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
<property name="testOnReturn" value="${redis.pool.testOnReturn}"/>
</bean>
<bean id = "jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1" value="${cache.redis.servers}"/>
<constructor-arg index="2" value="${cache.redis.port}" type="int"/>
</bean>
</beans>
3、简单使用
package com.test.springredis;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class TestSpringRedis {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
JedisPool jedisPool=(JedisPool)ctx.getBean("jedisPool");
Jedis jedis=jedisPool.getResource();
jedis.set("spring_test", "value");
System.out.println(jedis.get("spring_test"));
}
}