单位的老项目需要配置redis
1、使用的jar包
由于之前项目的springframework版本org.springframework.****-3.1.0 都是3.1的,使用新版都redis都报错,所有我用的都是最很久远的jar包
1、spring-data-redis-1.0.0.RELEASE.jar
2、jedis-2.1.0.jar
2、将这些JAR文件放入你的WEB-INF/lib
目录中。
3、applicationContext.xml 增加
<!-- Jedis 连接池配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxActive" value="128"/>
<property name="maxIdle" value="128"/>
<property name="minIdle" value="16"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
</bean>
<!-- Jedis 连接池 -->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1" value="localhost"/>
<constructor-arg index="2" value="6379"/>
</bean>
<!-- Jedis 连接工厂 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="usePool" value="true"/>
<property name="poolConfig" ref="jedisPoolConfig"/>
<property name="hostName" value="localhost"/>
<property name="port" value="6379"/>
</bean>
<!-- Redis 模板 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"/>
</bean>
4、测试:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
public class RedisTest {
public static void main(String[] args) {
try {
// 加载Spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取RedisTemplate bean
RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>) context.getBean("redisTemplate");
// 测试保存数据到Redis
String key = "Test";
String value = "测试value";
redisTemplate.opsForValue().set(key, value);
// 测试从Redis获取数据
Object result = redisTemplate.opsForValue().get(key);
System.out.println(" key========" + key + "Value======== " + result);
// 关闭Spring上下文
((ClassPathXmlApplicationContext) context).close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
唉 什么时候能做技术升级啊。。。。。。。。。。。。。。。。。。。。。。。