【开发心得】在SpringBoot体系中正确使用redisConfig

一、代码示例

redis配置

java 复制代码
package com.xxx.xxx.config.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.msgpack.jackson.dataformat.MessagePackFactory;
import org.springframework.beans.factory.annotation.Qualifier;
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.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class RedisConfig {
    @Value("${spring.redis.host}")
    private String HOSTNAME;

    @Value("${spring.redis.port}")
    private int PORT;

    @Value("${spring.redis.database}")
    private int DATABASE;

    @Value("${spring.redis.password}")
    private String PASSWORD;

    @Value("${spring.redis.timeout}")
    private long TIMEOUT;

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(HOSTNAME);
        config.setPort(PORT);
        config.setDatabase(DATABASE);
        config.setPassword(PASSWORD);

        LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
                .commandTimeout(Duration.ofMillis(TIMEOUT))
                .build();

        return new LettuceConnectionFactory(config, clientConfig);
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(@Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    public RedisTemplate<String, byte[]> messagePackRedisTemplate(@Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, byte[]> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setEnableDefaultSerializer(false);

        return template;
    }

    @Bean
    public ObjectMapper messagePackObjectMapper() {
        return new ObjectMapper(new MessagePackFactory())
                .registerModule(new JavaTimeModule())
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }

    /**
     *
     * RedisTemplate<String,Object>
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(@Qualifier("redisConnectionFactory") RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

application.yml

XML 复制代码
spring:
  redis:
    #数据库索引
    database: 0
    host: localhost
    port: 6379
    password: 你的密码
    #连接超时时间
    timeout: 5000

jackson配置

java 复制代码
package com.xxxx.config.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JsonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        return Jackson2ObjectMapperBuilder.json()
            .featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .modules(new JavaTimeModule())
            .build();
    }
}

二、详解

  1. 为什么单独配置messagePack?

为了在Redis中使用MessagePack进行高效序列化。

MessagePack是二进制序列化格式,比JSON:

  • 序列化/反序列化速度更快

  • 数据体积更小(节省30-50%空间)

  • 特别适合Redis这种内存数据库,节省内存

  1. Java8时间支持

.registerModule(new JavaTimeModule())

让ObjectMapper能正确处理LocalDateTime、LocalDate等Java 8时间类型

否则序列化时会抛异常

  1. 为什么单独json的禁用特性

.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)

日期不序列化为时间戳(如:1633046400000)

而是序列化为可读格式(如:"2021-10-01T00:00:00")

便于调试和跨语言兼容

相关推荐
MY_TEUCK1 天前
【Java 后端】SpringBoot 登录认证与会话跟踪实战(JWT + Filter/Interceptor)
java·开发语言·spring boot
今天长肉了吗1 天前
银行风控项目踩坑实录:指标跑了6小时,风险评分全挂了
java
计算机程序定制辅导1 天前
计算机小程序毕设实战-基于Spring Boot与微信小程序的考研资源共享平台设计与实现基于springboot+微信小程序的考研复习辅助平台【完整源码+LW+部署说明+演示视频,全bao一条龙等】
spring boot·微信小程序·小程序·课程设计
随读手机1 天前
多式联运信息交互平台完整方案(2026版)
java·ai·eclipse·云计算·区块链
许彰午1 天前
03-二叉树——从递归遍历到非递归实现
java·算法
nj01281 天前
Spring 循环依赖详解:三级缓存、早期引用、AOP 代理与懒加载
java·spring·缓存
野生技术架构师1 天前
2026年最全Java面试题及答案汇总(建议收藏,面试前看这篇就够了)
java·开发语言·面试
一只叫煤球的猫1 天前
ThreadForge 源码解读一:ThreadScope 如何把并发任务放进清晰边界?
java·面试·开源
洛_尘1 天前
Python 5:使用库
java·前端·python
程序员小假1 天前
HTTP3 性能更好,为什么内网微服务依然多用 HTTP2?HTTP2 内网优势是什么?
java·后端