SpringBoot Data-Redis存取bytes数组的方法

2023-03-08 1015点热度 0人点赞 0条评论

默认情况下SpringBoot的stringRedisTempalte只能存string,redisTemplate如果存入bytes也会报错,是因为找不到相应的ValueSerializer,或者用默认的StringRedisSerializer来序列化,导致bytes无法转成String而报错。

我们可以在Redis的配置文件下,指定相应的ValueSerializer。

RedisConfiguration.java的配置如下:

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.GenericToStringSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfiguration {

    @Bean(name="redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate();

        GenericToStringSerializer<String> keySerializer = new GenericToStringSerializer<>(String.class);
        template.setKeySerializer(keySerializer);
        template.setHashKeySerializer(keySerializer);

        StringRedisSerializer valueSerializer = new StringRedisSerializer();
        template.setValueSerializer(valueSerializer);
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.setConnectionFactory(factory);

        return template;
    }

    @Bean(name = "bytesRedisTemplate")
    public RedisTemplate<String, byte[]> bytesRedisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, byte[]> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        // 设置key和value的序列化规则
        redisTemplate.setValueSerializer(RedisSerializer.byteArray());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}

使用如下:

@Autowired
RedisTemplate<String, byte[]> redisTemplate;

byte[] bytes = file.getBytes();
// 存入bytes
redisTemplate.opsForValue().set(redisKey, bytes, 365, TimeUnit.DAYS);
// 读取
redisTemplate.opsForValue().get(redisKey);

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论