【发布时间】:2020-02-10 21:24:35
【问题描述】:
根据the doc,对于我们的自定义数据类型,建议使用Protobuf或类似的实现高效序列化。但是,我还发现内置数据类型(例如,GCounter)扩展了ReplicatedDataSerialization(参见code),根据scaladoc,
由 akka.cluster.ddata.protobuf.ReplicatedDataSerializer 序列化的 ReplicatedData 的标记特征。
我想知道我应该实现自己的序列化器实现还是简单地使用来自 akka 的序列化器实现。实施我自己的有什么好处?由于我的自定义数据类型实现(参见code 或以下)与PNCounter 非常相似,我觉得Akka 很适合我的情况。
import akka.cluster.ddata.{GCounter, Key, ReplicatedData, ReplicatedDataSerialization, SelfUniqueAddress}
/**
* Denote a fraction whose numerator and denominator are always growing
* Prefer such a custom ddata structure over using 2 GCounter separately is to get best of both worlds:
* As lightweight as a GCounter, and can update/get both values at the same time like a PNCounterMap
* Implementation-wise, it borrows from PNCounter a lot
*/
case class FractionGCounter(
private val numerator: GCounter = GCounter(),
private val denominator: GCounter = GCounter()
) extends ReplicatedData
with ReplicatedDataSerialization {
type T = FractionGCounter
def value: (BigInt, BigInt) = (numerator.value, denominator.value)
def incrementNumerator(n: Int)(implicit node: SelfUniqueAddress): FractionGCounter = copy(numerator = numerator :+ n)
def incrementDenominator(n: Int)(implicit node: SelfUniqueAddress): FractionGCounter =
copy(denominator = denominator :+ n)
override def merge(that: FractionGCounter): FractionGCounter =
copy(numerator = this.numerator.merge(that.numerator), denominator = this.denominator.merge(that.denominator))
}
final case class FractionGCounterKey(_id: String) extends Key[FractionGCounter](_id) with ReplicatedDataSerialization
【问题讨论】: