在具有缓存系统支持的数据库层的项目中,创建新条目时需要更新数据库和外部服务(缓存)。当采用 Ballerina 交易来实现这一目标时,会遇到一些挑战。如果事务过程中发生错误,会导致数据不一致,因为虽然数据库中的更改在回滚过程中有效恢复,但相应的缓存条目保持不变
transaction{
_ = check createRole(roleName);
_ = check ketoWriteEP->createRelationTuple(payload);
check commit;
}
function createRole(string roleName, ){
sql:ParameterizedQuery insertQuery = createAppRoleQuery(roleName, appId, organizationId);
sql:ExecutionResult result = check dbClient->execute(insertQuery);
utils:RoleDO role = {role_name: roleName};
error? response = localcache:addRoleToCache(roleName);
}
事务失败时如何手动回滚Cache?
这可以通过多种方式实现,
可以注册回滚处理程序,详细信息如下:https://ballerina.io/learn/by-example/commit-rollback-handlers/。这允许实现自定义函数来恢复缓存更改,并且可以注册该函数以在启动回滚时触发。 (注意:回滚处理程序和提交处理程序仅为该特定事务块注册)
可以在
on fail
块中手动回滚缓存,如下所示:
transaction{
_ = check createRole(roleName);
_ = check ketoWriteEP->createRelationTuple(payload);
check commit;
} on fail error e {
// Check weather the error is due to client invocation
if e !is sql:Error {
// Remove value from the cache
}
}