使用redis存储Java对象,首先要将Java对象进行序列化
方案一:自定义RedisTemplate的序列化对象
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
/**
* 自定义RedisTemplate,修改其序列化方法
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){
// 创建RedisTemplate对象
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 设置连接工厂
template.setConnectionFactory(connectionFactory);
// 创建JSON序列化工具
GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
// 设置Key的序列化
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
// 设置Value的序列化
template.setValueSerializer(jsonRedisSerializer);
template.setHashValueSerializer(jsonRedisSerializer);
// 返回
return template;
}
}
方案二:使用RedisTemplate的子类StringRedisTemplate,需要手动序列化和反序列化
测试:加入user对象
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.redis.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
@SpringBootTest
class RedisDemoApplicationTests {
//序列化工具
private static final ObjectMapper mapper = new ObjectMapper();
@Autowired
private RedisTemplate<String,Object> redisTemplate;
@Autowired
StringRedisTemplate stringRedisTemplate;
@Test
void testSaveUser() throws JsonProcessingException {
//方案一
redisTemplate.opsForValue().set("user:100", new User("虎哥", 21));
// 获取数据
User o = (User) redisTemplate.opsForValue().get("user:100");
System.out.println("100 = " + o);
//方案二
User user = new User("阿伟", 23);
//JSON序列化
String s = mapper.writeValueAsString(user);
stringRedisTemplate.opsForValue().set("user:200",s);
String strJson = stringRedisTemplate.opsForValue().get("user:200");
//JSON反序列化
System.out.println("200 = "+mapper.readValue(strJson,User.class));
}
}
运行结果
推荐使用第二种,后续可将序列化和反序列化封装工具类即可,
第一中的话在序列化的时候会生成class属性,占用内存,开销大