redis与spring集成--spring-data-redis

来源:互联网 发布:全球复制软件 编辑:程序博客网 时间:2024/04/30 06:33

 1.需要的jar包

 

jar包方面的话,替换的时候自己测试吧,之前使用的时候自己打的一些jar包,不知怎么的死活无法连接,后来使用maven下载包的时候使用的这些,如果不清楚的话,推荐使用maven,配置依赖即可

    <dependency>          <groupId>org.springframework.data</groupId>          <artifactId>spring-data-redis</artifactId>          <version>1.7.1.RELEASE</version>      </dependency>      <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-core</artifactId>          <version>4.2.5.RELEASE</version>      </dependency>            <dependency>          <groupId>redis.clients</groupId>          <artifactId>jedis</artifactId>          <version>2.8.0</version>      </dependency> 

2.spring-application.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"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"/><!-- jedis pool配置 --><bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"><!-- 最大空闲时间 --><property name="maxIdle" value="${redis.maxIdle}" /><!-- 最大等待毫秒数--><property name="maxWaitMillis" value="${redis.maxWait}" /><!-- 连接有效性验证 --><property name="testOnBorrow" value="${redis.testOnBorrow}" /></bean><!-- redis服务器中心 --><bean id="connectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"><property name="poolConfig" ref="poolConfig" /><property name="port" value="${redis.port}" /><property name="hostName" value="${redis.host}" /><property name="password" value="${redis.password}" /><property name="timeout" value="${redis.timeout}"></property></bean><!-- redis客户端模板 --><bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"><!-- 注入连接工厂 --><property name="connectionFactory" ref="connectionFactory" /><!-- 配置key序列化类 --><property name="keySerializer"><beanclass="org.springframework.data.redis.serializer.StringRedisSerializer" /></property><!-- 配置value序列化类 --><property name="valueSerializer"><beanclass="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /></property></bean></beans>
redis.properties配置
#redis configredis.host=127.0.0.1redis.port=6379redis.password=redisredis.maxIdle=100 redis.maxWait=1000 redis.testOnBorrow=true redis.timeout=100000

3.实例代码

import java.util.Date;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.dao.DataAccessException;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.RedisSerializer;import com.vclouds.redis.Bean;public class Dao{private RedisTemplate<String,Object> redisTemplate;public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate){this.redisTemplate = redisTemplate;}public Dao(){ApplicationContext app = new ClassPathXmlApplicationContext("classpath:spring-application.xml");System.out.println(app);redisTemplate = (RedisTemplate<String, Object>) app.getBean("redisTemplate");}@Testpublic void test(){new Dao();final Bean b = new Bean(1,"hello",new Date());redisTemplate.execute(new RedisCallback<Boolean>(){                        /**设置string类型的key-value*/public Boolean doInRedis(RedisConnection connection)throws DataAccessException{RedisSerializer<String> serializer = redisTemplate.getStringSerializer();byte[] key = serializer.serialize("hello");byte[] value = serializer.serialize("world");try{connection.set(key, value);} catch (Exception e){e.printStackTrace();return false;}return true;}});String str = redisTemplate.execute(new RedisCallback<String>(){<pre name="code" class="java">    /**根据string类型的key获取value*/                        public String doInRedis(RedisConnection connection)                                throws DataAccessException{                                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();                                byte[] key = serializer.serialize("hello");                                return serializer.deserialize(connection.get(key));                        }                 });                 System.out.println(str);                 }             } 


4.常见问题

       需要注意的是这种使用方式需要将每次存放的值转换成byte数组进行操作,获取值的时候再将获取到的byte数组转为需要的类型进行操作,如果要建对象使用字符串存储,也同样需要将之转换成byte数组,但是该对象必须实现Serializable接口。



1 0