我很好奇FoundationDB如何处理存在多个事务试图更新相同密钥的情况?
如果一个客户端执行此事务:
db.run((Transaction tr) -> {
tr.set(Tuple.from("key").pack(), Tuple.from("valueA").pack());
return null;
});当另一个客户端执行冲突的事务时:
db.run((Transaction tr) -> {
tr.set(Tuple.from("key").pack(), Tuple.from("valueB").pack());
return null;
});在FoundationDB内部会发生什么来解决冲突?
发布于 2018-05-24 23:18:50
最近,我一直在探索和测试FoundationDB (我猜现在每个人都在玩它),作为我探索的一部分,我做了一些简单的测试。其中一个应该回答你的问题:
因此,下面是一个示例(希望您不会介意Scala):
import com.apple.foundationdb._
import com.apple.foundationdb.tuple._
import resource.managed
import scala.collection.mutable
import scala.util.Random
object Example {
val THREAD_COUNT = 1
@volatile var v0: Long = 0
@volatile var v1: Long = 0
@volatile var v2: Long = 0
@volatile var v3: Long = 0
@volatile var v4: Long = 0
def doJob(db: Database, x: Int): Unit = {
db.run((tr) => {
val key = Tuple.from("OBJ", Long.box(100)).pack()
val current = Tuple.fromBytes(tr.get(key).join())
if (Random.nextInt(100) < 2) {
out(current)
}
val next = mutable.ArrayBuffer(current.getLong(0), current.getLong(1), current.getLong(2), current.getLong(3), current.getLong(4))
if (x == 1 && v1 == next(1)) { println(s"again: $v1, v0=$v0, 0=${next(0)}")}
if (x == 0 && v0 > next(0)) { out(current); ??? } else { v0 = next(0)}
if (x == 1 && v1 > next(1)) { out(current); ??? } else { v1 = next(1)}
if (x == 2 && v2 > next(2)) { out(current); ??? } else { v2 = next(2)}
if (x == 3 && v3 > next(3)) { out(current); ??? } else { v3 = next(3)}
if (x == 4 && v4 > next(4)) { out(current); ??? } else { v4 = next(4)}
next.update(x, next(x) + 1)
val nv = Tuple.from(next.map(v => Long.box(v)) :_*)
tr.set(key, nv.pack())
})
}
def main(args: Array[String]): Unit = {
if (THREAD_COUNT > 5) {
throw new IllegalArgumentException("")
}
val fdb: FDB = FDB.selectAPIVersion(510)
for (db <- managed(fdb.open())) {
// Run an operation on the database
db.run((tr) => {
for (x <- 0 to 10000) {
val k = Tuple.from(s"OBJ", x.toLong.underlying()).pack()
val v = Tuple.from(Long.box(0), Long.box(0), Long.box(0), Long.box(0), Long.box(0)).pack()
tr.set(k, v)
null
}
})
val threads = (0 to THREAD_COUNT).map { x =>
new Thread(new Runnable {
override def run(): Unit = {
while (true) {
try {
doJob(db, x)
} catch {
case t: Throwable =>
t.printStackTrace()
}
}
}
})
}
threads.foreach(_.start())
threads.foreach(_.join())
}
}
private def out(current: Tuple) = {
println("===")
println((v0, v1, v2, v3, v4))
println((Thread.currentThread().getId, current))
}
}因此,这个东西允许您启动几个线程写入同一个对象。在其他实验中留下了一些统一要求的代码,忽略它(或者用于您自己的实验)。
这段代码生成您的线程,然后每个线程从键(0,1,0,0,0)中读取五个长的元组,如("OBJ", 100),然后递增与线程号对应的值,然后将其写回,并增加一个易失性计数器。
以下是我的观察:
println(s"again: $v1, v0=$v0, 0=${next(0)}")因此,本质上,当冲突发生时,FoundationDB客户端正在尝试提交事务,直到事务成功。您可以在文档的本章中找到更多详细信息。然后看看体系结构概述图
还请注意,您的事务只是函数。希望- 幂等函数。
您应该知道,在许多情况下,您可以通过对您的值使用原子运算来避免冲突。
希望这能回答你的问题。
我建议您阅读所有的官方文件,这样您就可以在其中找到许多有趣的东西,包括数据库开发人员考虑CAP定理、冷分布式数据结构的好例子以及许多其他技术细节和有趣的东西。
https://stackoverflow.com/questions/50519331
复制相似问题