整合spring、redis

来源:互联网 发布:阿里云 证书被ios信任 编辑:程序博客网 时间:2024/06/07 03:01

一、依赖的两个jar包

<dependency>
   <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-redis</artifactId>
  <version>1.5.0.RELEASE</version>
   </dependency>
<dependency>
 <groupId>com.jd.adword.pipe</groupId>
 <artifactId>jedis</artifactId>
 <version>2.8.0</version>
   </dependency>


二、 配置文件:

<?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"
xsi:schemaLocation="  
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


<context:property-placeholder location="classpath:redis.properties" />
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxActive" value="${redis.pool.maxActive}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="maxWait" value="${redis.pool.maxWait}" />
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
</bean>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis1.ip}" />
<constructor-arg index="1" value="${redis.port}"
type="int" />
</bean>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis2.ip}" />
<constructor-arg index="1" value="${redis.port}"
type="int" />
</bean>
</list>
</constructor-arg>
</bean>
</beans>  

三、应用程序

private ApplicationContext app;  
private ShardedJedisPool pool;  
  
@Before  
public void before() throws Exception {  
    app = new ClassPathXmlApplicationContext("applicationContext.xml");  
    pool = (ShardedJedisPool) app.getBean("shardedJedisPool");  
}  
  
@Test  
public void test() {  
  
    // 从池中获取一个Jedis对象  
    ShardedJedis jedis = pool.getResource();  
    String keys = "name";  
    String value = "snowolf";  
    // 删数据  
    jedis.del(keys);  
    // 存数据  
    jedis.set(keys, value);  
    // 取数据  
    String v = jedis.get(keys);  
  
    System.out.println(v);  
  
    // 释放对象池  
    pool.returnResource(jedis);  
  
    assertEquals(value, v);  

0 0
原创粉丝点击