redis配置类:

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {

    @Bean("redissonClient")
    public RedissonClient redissonClient(ConfigurableApplicationContext applicationContext, RedisClientConfigProperties properties) {
        Config config = new Config();
        //也可以用别的进行序列化反序列化
         config.setCodec(new RedisCodec());

        config.useSingleServer()
                .setAddress("redis://" + properties.getHost() + ":" + properties.getPort())
            // 没密码就注起来
//                .setPassword(properties.getPassword())
                .setConnectionPoolSize(properties.getPoolSize())
                .setConnectionMinimumIdleSize(properties.getMinIdleSize())
                .setIdleConnectionTimeout(properties.getIdleTimeout())
                .setConnectTimeout(properties.getConnectTimeout())
                .setRetryAttempts(properties.getRetryAttempts())
                .setRetryInterval(properties.getRetryInterval())
                .setPingConnectionInterval(properties.getPingInterval())
                .setKeepAlive(properties.isKeepAlive())
        ;

        return Redisson.create(config);
    }

    static class RedisCodec extends BaseCodec {
		
        // 序列化方法
        private final Encoder encoder = in -> {
            ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
            try {
                ByteBufOutputStream os = new ByteBufOutputStream(out);
                JSON.writeJSONString(os, in, SerializerFeature.WriteClassName);
                return os.buffer();
            } catch (IOException e) {
                out.release();
                throw e;
            } catch (Exception e) {
                out.release();
                throw new IOException(e);
            }
        };
		
        //反序列化方法
        private final Decoder<Object> decoder = (buf, state) -> {
            try {
                ByteBufInputStream inputStream = new ByteBufInputStream(buf);
                byte[] bytes = new byte[inputStream.available()];
                inputStream.read(bytes);
                String jsonString = new String(bytes);
                return JSON.parse(jsonString, com.alibaba.fastjson.parser.Feature.SupportAutoType);
            } catch (Exception e) {
                throw new RuntimeException("Failed to decode object", e);
            }
        };

        @Override
        public Decoder<Object> getValueDecoder() {
            return decoder;
        }

        @Override
        public Encoder getValueEncoder() {
            return encoder;
        }

    }

}

至于redis的配置可以写一个专门的类从配置文件中读取配置,并注入进来如RedisProperties,代码比较简单我就不展示了。

下面是redis用fastjson和fastjson2序列化和反序列化的步骤:

先是fastjson:

关键步骤:

  1. 序列化(Encoder)
    • 使用 JSON.writeJSONString() 方法
    • 添加 SerializerFeature.WriteClassName 保存类型信息
  2. 反序列化(Decoder)
    • 使用 JSON.parse() 方法
    • 启用 Feature.SupportAutoType 支持自动类型识别

代码参考上面的。

Fastjson2 实现方式

如果要使用 Fastjson2,代码会是这样的:

依赖配置:

<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.43</version>
</dependency>

关键代码:

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.JSONReader;

static class RedisCodecFastjson2 extends BaseCodec {
    
    // Fastjson2 序列化
    private final Encoder encoder = in -> {
        ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
        try {
            ByteBufOutputStream os = new ByteBufOutputStream(out);
            // Fastjson2 使用 JSONWriter.Feature.WriteClassName
            JSON.writeTo(os, in, JSONWriter.Feature.WriteClassName);
            return os.buffer();
        } catch (IOException e) {
            out.release();
            throw e;
        } catch (Exception e) {
            out.release();
            throw new IOException(e);
        }
    };

    // Fastjson2 反序列化
    private final Decoder<Object> decoder = (buf, state) -> {
        try {
            ByteBufInputStream inputStream = new ByteBufInputStream(buf);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            String jsonString = new String(bytes);
            // Fastjson2 使用 JSONReader.Feature.SupportAutoType
            return JSON.parseObject(jsonString, Object.class, 
                JSONReader.Feature.SupportAutoType);
        } catch (Exception e) {
            throw new RuntimeException("Failed to decode object", e);
        }
    };
}

两个版本的主要区别

1. 包名和类名

  • Fastjson 1.x: com.alibaba.fastjson.JSON
  • Fastjson2: com.alibaba.fastjson2.JSON

2. 序列化方法

  • Fastjson 1.x: JSON.writeJSONString(outputStream, object, SerializerFeature.WriteClassName)
  • Fastjson2: JSON.writeTo(outputStream, object, JSONWriter.Feature.WriteClassName)

3. 反序列化方法

  • Fastjson 1.x: JSON.parse(jsonString, Feature.SupportAutoType)
  • Fastjson2: JSON.parseObject(jsonString, Object.class, JSONReader.Feature.SupportAutoType)

4. 特性配置

  • Fastjson 1.x:
    • SerializerFeature.WriteClassName
    • Feature.SupportAutoType
  • Fastjson2:
    • JSONWriter.Feature.WriteClassName
    • JSONReader.Feature.SupportAutoType

完整的迁移步骤(要从fastjson-》fastjson2)

步骤1:更新依赖

<!-- 移除 Fastjson 1.x -->
<!--
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version>
</dependency>
-->

<!-- 添加 Fastjson2 -->
<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.43</version>
</dependency>

步骤2:更新导入语句

// 替换导入
// import com.alibaba.fastjson.JSON;
// import com.alibaba.fastjson.serializer.SerializerFeature;
// import com.alibaba.fastjson.parser.Feature;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.JSONReader;

步骤3:更新序列化代码

// Fastjson 1.x → Fastjson2
JSON.writeJSONString(os, in, SerializerFeature.WriteClassName);
// 改为
JSON.writeTo(os, in, JSONWriter.Feature.WriteClassName);

步骤4:更新反序列化代码

// Fastjson 1.x → Fastjson2  
JSON.parse(jsonString, Feature.SupportAutoType);
// 改为
JSON.parseObject(jsonString, Object.class, JSONReader.Feature.SupportAutoType);

性能和安全性对比

Fastjson2 的优势:

  1. 性能提升: 序列化和反序列化速度更快
  2. 内存优化: 更好的内存使用效率
  3. 安全性: 更严格的 AutoType 安全检查
  4. API 设计: 更清晰的 API 设计

注意事项:

  1. 兼容性: Fastjson2 不是 100% 向后兼容
  2. AutoType 安全: 两个版本都需要谨慎使用 AutoType 功能
  3. 测试: 迁移后需要充分测试序列化/反序列化功能
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐