redis+springboot

冷风5997 / 2024-07-12 / 原文

可以看到value显示为二进制,这是由于redisTemplate默认使用jdk序列化导致的,这种方式生成的数据较大,性能较低,且只有Java应用能够反序列化。本文将用fastjson2作为序列化方式。

fastjson2作为序列化方式
pom文件中引入fastjson2:

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>2.0.45</version>
</dependency>
 增加RedisConfig配置类:

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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.StringRedisSerializer;
 
/**
 * redis配置
 *
 * @Author: gusy
 */
@Slf4j
@Configuration
public class RedisConfig {
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // 使用Fastjson2序列化器
        GenericFastJsonRedisSerializer redisSerializer = new GenericFastJsonRedisSerializer();
        // 设置 value 的序列化规则和 key 的序列化规则
        template.setValueSerializer(redisSerializer);
        template.setHashValueSerializer(redisSerializer);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        log.info("redis自定义配置启动成功!");
        return template;
    }
}