如何在Cassandra中执行多个操作的事务

时间:2016-08-01 14:43:17

标签: c++ cassandra

我想在Cassandra中执行具有多个写操作(~5个插入/更新到不同表)的事务,但如果其中任何一个失败,则不应写入其余部分(回滚每个操作或使整个事务失败)

请让我知道在Cassandra执行此操作的正确方法是什么,以及如何操作(欢迎提供示例)。

1 个答案:

答案 0 :(得分:1)

是的,您可以使用已记录的批处理功能以原子方式完成此操作。请注意,您确实会受到影响。请参阅C ++驱动程序的BATCH Statements文档部分。

这是一个如何在C ++中执行此操作的示例,取自上面的文档链接。它演示了如何批量处理INSERTUPDATEDELETE

/* 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);