You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB与Redis的Java对象自定义序列化反序列化方案问询

Redis 自定义字段序列化/反序列化实现

Redis的序列化处理可以通过Spring Data Redis Serializer实现,支持全局或字段级的自定义转换。

方案1:字段级自定义序列化器

针对BigDecimal和Date类型单独实现序列化器,配置到RedisTemplate中。

1. 自定义BigDecimal Redis序列化器

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.nio.charset.StandardCharsets;

public class CustomBigDecimalRedisSerializer implements RedisSerializer<BigDecimal> {
    private static final DecimalFormat CURRENCY_FORMAT = new DecimalFormat("#,##0.00");
    static {
        CURRENCY_FORMAT.setGroupingUsed(true);
        CURRENCY_FORMAT.setDecimalSeparator(',');
        CURRENCY_FORMAT.setGroupingSeparator('.');
    }

    @Override
    public byte[] serialize(BigDecimal value) throws SerializationException {
        if (value == null) return new byte[0];
        return CURRENCY_FORMAT.format(value).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public BigDecimal deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) return null;
        String str = new String(bytes, StandardCharsets.UTF_8);
        try {
            return (BigDecimal) CURRENCY_FORMAT.parse(str);
        } catch (Exception e) {
            throw new SerializationException("Failed to deserialize BigDecimal: " + str, e);
        }
    }
}

2. 自定义Date Redis序列化器

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.nio.charset.StandardCharsets;

public class CustomDateRedisSerializer implements RedisSerializer<Date> {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");

    @Override
    public byte[] serialize(Date value) throws SerializationException {
        if (value == null) return new byte[0];
        return DATE_FORMAT.format(value).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public Date deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) return null;
        String str = new String(bytes, StandardCharsets.UTF_8);
        try {
            return DATE_FORMAT.parse(str);
        } catch (Exception e) {
            throw new SerializationException("Failed to deserialize Date: " + str, e);
        }
    }
}

3. 配置RedisTemplate

将自定义序列化器配置到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.StringRedisSerializer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

@Configuration
public class RedisSerializerConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 键使用字符串序列化器
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        // 为指定类型绑定自定义序列化器
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer() {
            @Override
            public byte[] serialize(Object value) throws SerializationException {
                if (value instanceof BigDecimal) {
                    return new CustomBigDecimalRedisSerializer().serialize((BigDecimal) value);
                } else if (value instanceof Date) {
                    return new CustomDateRedisSerializer().serialize((Date) value);
                }
                return super.serialize(value);
            }

            @Override
            public Object deserialize(byte[] bytes) throws SerializationException {
                // 若需精准反序列化,可根据字节内容判断类型,或直接使用Dummy类专属序列化器
                return super.deserialize(bytes);
            }
        });

        template.afterPropertiesSet();
        return template;
    }
}

方案2:Dummy类专属序列化器

如果只需要处理Dummy对象,可以直接实现RedisSerializer<Dummy>,手动控制每个字段的序列化反序列化逻辑,类似Jackson的注解方式,但代码更集中。


内容的提问来源于stack exchange,提问作者Paul Marcelin Bejan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:20:36