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

如何使用CompactSerializer序列化Map类型字段至Hazelcast Map?

解决Hazelcast 5.1 CompactSerializer序列化Map字段的问题

Hazelcast 5.1的Compact序列化API确实没有直接提供Map/Set这类集合类型的读写方法,需要手动拆解集合元素,逐个完成序列化与反序列化。以下是完整的实现方案:

完整的UserSerializer实现

data class User(
    val id: String,
    val authoritiesByOrgId: Map<String, Set<String>>
)
class UserSerializer : CompactSerializer<User> {

    override fun read(reader: CompactReader): User {
        val id = reader.readString("id")
        // 读取Map的条目总数
        val mapSize = reader.readInt("auth_map_size")
        val authoritiesByOrgId = mutableMapOf<String, Set<String>>()

        repeat(mapSize) { index ->
            // 读取当前条目的键
            val orgId = reader.readString("auth_key_$index")
            // 读取对应Set的元素数量
            val setSize = reader.readInt("auth_set_size_$index")
            val authorities = mutableSetOf<String>()
            // 逐个读取Set中的元素
            repeat(setSize) { setIndex ->
                authorities.add(reader.readString("auth_val_${index}_$setIndex"))
            }
            authoritiesByOrgId[orgId] = authorities
        }

        return User(id, authoritiesByOrgId)
    }

    override fun write(writer: CompactWriter, user: User) {
        writer.apply {
            writeString("id", user.id)
            // 先写入Map的条目总数
            writeInt("auth_map_size", user.authoritiesByOrgId.size)
            
            user.authoritiesByOrgId.entries.forEachIndexed { index, entry ->
                // 写入当前条目的键
                writeString("auth_key_$index", entry.key)
                // 写入对应Set的元素数量
                writeInt("auth_set_size_$index", entry.value.size)
                // 逐个写入Set中的元素
                entry.value.forEachIndexed { setIndex, authority ->
                    writeString("auth_val_${index}_$setIndex", authority)
                }
            }
        }
    }

    // 必须实现该方法,返回全局唯一的类型标识
    override fun getTypeName(): String {
        return "com.yourpackage.User"
    }
}

实现说明

  • 核心逻辑:Compact序列化是基于明确字段的序列化方式,不支持自动处理嵌套集合类型,因此需要将Map拆解为「键+对应Set的元素」,通过索引区分不同条目,保证字段名称唯一不冲突。
  • Set的处理:Set同样需要先写入元素数量,再逐个写入元素;反序列化时按读取的数量依次获取元素,组装成Set。
  • 类型名称:getTypeName方法返回的字符串必须全局唯一,Hazelcast通过这个标识匹配对应的序列化器。

内容的提问来源于stack exchange,提问作者KevinS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:57:32