使用Spring-data-redis
一、Springboot整合redis
1.引入相关依赖
2.配置文件中配置相关redis信息
3.配置redis序列化器(spring默认会使用java的序列化机制,但是不推荐,因为会保存对象信息,造成存储空间浪费)
package com.zhaozhenhua.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
/***
* 编写自己的 RedisTemplate
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
/**
* 配置具体的序列化方式
*/
//JSON序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);
/*om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);*/
jackson2JsonRedisSerializer.setObjectMapper(om);
//String序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
//value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
//hash的value序列化采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
4.使用StringRedisTemplate(实现了键和值都使用string方式序列化),如果需要放入对象的时候,自己手动进行序列化和反序列化。手动序列化和反序列化可以使用alibabafastjson
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
void f2(){
ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
User user = new User("张三", 18);
//使用fastjson将对象进行序列化
String s = JSON.toJSONString(user);
stringStringValueOperations.set("user",s);
String s1 = stringStringValueOperations.get("user");
//使用fastjson将字符串反序列成对象
User parse = JSON.parseObject(s1,User.class);
System.out.println(parse);
}