一、简介
在 spring与redis整合(一)中,介绍了采用原生的jedis方式,进行redis与spring的整合。
在本文,将介绍采用spring封装的redisTemple(spring-date-redis)方式,进行redis操作。
二、配置
1、jedis池配置
redis.clients.jedis.JedisPoolConfig,参数有:
a)maxTotal,池中最多可以有多少个jedis实例,默认值是8
b)maxIdle,池中最多有多少个空闲的jedis实例,默认值是8
c)minIdle,池中最小有多少个空闲的jedis实例,默认值是0
d)maxWaitMillis,获取jedis实例的最大等待毫秒数,默认值是-1
如:<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" p:maxTotal="6000" p:maxIdle="300" p:minIdle="100" p:maxWaitMillis="1500" />2、JedisConnectionFactory配置
org.springframework.data.redis.connection.jedis.JedisConnectionFactory,参数有:
a) hostname,redis安装地址;
b)port,端口;
c)poolConfig,jedis的池配置;
如:
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:hostName="127.0.0.1" p:port="6379" p:database="0" p:poolConfig-ref="jedisPoolConfig" />
3、序列化方式
spring data redis有4种序列化方式,
a)org.springframework.data.redis.serializer.StringRedisSerializer ,字符串方式序列化,即
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
b)org.springframework.data.redis.serializer.JdkSerializationRedisSerializer ,jdk默认的序列化方式,即
<bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
c)Jackson2JsonRedisSerializer ,jackson的json序列化方式,需要指定序列化的类型。如
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Student>(Student.class)); ValueOperations<String,Student> valOps = redisTemplate.opsForValue(); valOps.set("ss2",new Student(2)); Student st = valOps.get("s2");
d)OxmSerializer, xml方式进行序列化,如
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); Map<String,Object> properties = new HashMap<String, Object>(); properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //设置缩进 properties.put(Marshaller.JAXB_ENCODING,"utf-8"); //设置编码 jaxb2Marshaller.setMarshallerProperties(properties);//设置Marshaller属性 jaxb2Marshaller.setClassesToBeBound(Student.class); redisTemplate.setValueSerializer(new OxmSerializer(jaxb2Marshaller,jaxb2Marshaller)); ValueOperations<String,Student> stuValOps = redisTemplate.opsForValue(); stuValOps.set("xs2",new Student(4)); Student xs2 = stuValOps.get("xs2"); System.out.println(xs2);
4、RedisTemplate配置
org.springframework.data.redis.core.RedisTemplate,redisTemplate是我们操作redis的入口之一,内有参数:
a)connectionFactory,jedis的连接工厂;
b)keySerializer, key的序列化方式;
c)valueSerializer,value的序列化方式;
d)hash