使用自定义的序列化器
使用RedisTemplate默认的序列化器发送数据,会将key全都当成Object处理,从而按照对象的方式转成json格式发送到服务器,这样会导致两个问题。一是不方便阅读,二是会大大浪费内存。因此,建议自定义RedisTemplate的序列化器,将key按照String方式传输,value按照json方式传输,下面是代码。
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;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {// 创建RedisTemplate<String, Object>对象RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();// 设置RedisTemplate的连接工厂redisTemplate.setConnectionFactory(redisConnectionFactory);// 设置RedisTemplate的序列化器GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();// key和hashKey的序列化器采用StringredisTemplate.setKeySerializer(RedisSerializer.string());redisTemplate.setHashKeySerializer(RedisSerializer.string());// value和hashValue的序列化器采用jsonRedisSerializerredisTemplate.setValueSerializer(jsonRedisSerializer);redisTemplate.setHashValueSerializer(jsonRedisSerializer);return redisTemplate;}
}
使用StringRedisTemplate
上述方法在传输数据时候,存在一个问题。上述方法在传输在redis数据库中时候,会将数据类型也传上去,占用了的很大的内存,如下图所示:
@Testvoid contextLoads() {User u = new User("李斯", 20);redisTemplate.opsForValue().set("newName", u);System.out.println(redisTemplate.opsForValue().get("newName"));}
解决方案是使用StringRedisTemplate:
@AutowiredStringRedisTemplate stringRedisTemplate;// json工具static final ObjectMapper objectMapper = new ObjectMapper();@Testvoid testStringRedisTemplate() throws Exception {User u = new User("李斯", 20);// 将对象转换为json字符串String json = objectMapper.writeValueAsString(u);stringRedisTemplate.opsForValue().set("user:200", json);// 从redis中取出json字符串String result = stringRedisTemplate.opsForValue().get("user:200");// 将json字符串转换为对象User user = objectMapper.readValue(result, User.class);System.out.println(user);}