如何在Cassandra中使用多个操作执行事务
问题描述:
我想在Cassandra中执行具有多个写入操作(〜5个插入/更新到不同表格)的事务,但是如果其中任何一个失败,则其余部分不应写入(或者回滚每个操作或者失败整个事务)。如何在Cassandra中使用多个操作执行事务
请让我知道什么是在Cassandra中执行此操作的正确方法以及如何执行此操作(欢迎举例)。
答
是的,您可以使用记录的批处理功能来自动完成此操作。请注意,你确实对性能产生了影响。请参阅C++驱动程序的BATCH Statements文档部分。
下面是一个如何在C++中执行此操作的示例,取自上面的文档链接。它演示展示了如何批量的INSERT
,UPDATE
和DELETE
在一起:
/* This logged batch will makes sure that all the mutations eventually succeed */
CassBatch* batch = cass_batch_new(CASS_BATCH_TYPE_LOGGED);
/* Statements can be immediately freed after being added to the batch */
{
CassStatement* statement
= cass_statement_new(cass_string_init("INSERT INTO example1(key, value) VALUES ('a', '1')"), 0);
cass_batch_add_statement(batch, statement);
cass_statement_free(statement);
}
{
CassStatement* statement
= cass_statement_new(cass_string_init("UPDATE example2 set value = '2' WHERE key = 'b'"), 0);
cass_batch_add_statement(batch, statement);
cass_statement_free(statement);
}
{
CassStatement* statement
= cass_statement_new(cass_string_init("DELETE FROM example3 WHERE key = 'c'"), 0);
cass_batch_add_statement(batch, statement);
cass_statement_free(statement);
}
CassFuture* batch_future = cass_session_execute_batch(session, batch);
/* Batch objects can be freed immediately after being executed */
cass_batch_free(batch);
/* This will block until the query has finished */
CassError rc = cass_future_error_code(batch_future);
printf("Batch result: %s\n", cass_error_desc(rc));
cass_future_free(batch_future);
嗨亚伦,感谢您的完整的答案。它可能是卡桑德拉交易吗?既然您提到了使用Cassandra的批处理功能的性能问题,那么有没有其他解决方案具有更好的性能?先谢谢你。 – gliatsos
@GeorgeL这与其他数据库中的事务的实现类似。主要区别在于,在Cassandra中,性能受到影响(大约30%左右),因为它必须使用协调节点才能与可能受批处理影响的所有节点通信。而在RDBMS世界中,将多个语句批量处理为“事务”被认为是一种性能改进。你可以做更少的性能命中所谓的“未记录的批处理”,但如果你的批处理语句影响多个分区,未记录的批处理不能保证原子性。 – Aaron