污网站公司网站,网站建设广告费 科目,建设类似衣联网的网站,成都网站建设 3e网络使用装饰器启用事务事务传播机制事务补偿机制确保数据库与缓存数据一致性使用装饰器启用事务import { Database } from vona-module-a-orm;class ServicePost {Database.transaction()async transaction() {// insertconst post await this.scope.model.post.insert({title: P…使用装饰器启用事务事务传播机制事务补偿机制确保数据库与缓存数据一致性使用装饰器启用事务import { Database } from vona-module-a-orm;class ServicePost {Database.transaction()async transaction() {// insertconst post await this.scope.model.post.insert({title: Post001,});// updateawait this.scope.model.post.update({id: post.id,title: Post001-Update,});}}手工启用事务1. 使用当前数据源class ServicePost {async transactionManually() {const db this.bean.database.current;await db.transaction.begin(async () {await this.scope.model.post.update({ id: 1, title: Post001_Update });});}}2. 使用指定数据源class ServicePost {async transactionManually() {const db this.bean.database.getDb({ clientName: default });await db.transaction.begin(async () {const modelPost this.scope.model.post.newInstance(db);await modelPost.update({ id: 1, title: Post001_Update });});}}事务参数class ServicePost {Database.transaction({ isolationLevel: READ_COMMITTED, propagation: REQUIRED})async transaction() {...}}class ServicePost {async transactionManually() {const db this.bean.database.getDb({ clientName: default });await db.transaction.begin(async () {...},{ isolationLevel: READ_COMMITTED, propagation: REQUIRED,});}}事务参数isolationLevel名称 说明DEFAULT 数据库相关的缺省isolationLevelREAD_UNCOMMITTEDREAD_COMMITTEDREPEATABLE_READSERIALIZABLESNAPSHOT事务参数propagationVona ORM 支持数据库事务传播机制名称 说明REQUIRED 默认的事务传播级别。如果当前存在事务, 则加入该事务。如果当前没有事务, 则创建一个新的事务SUPPORTS 如果当前存在事务则加入该事务. 如果当前没有事务, 则以非事务的方式继续运行MANDATORY 强制性。如果当前存在事务, 则加入该事务。如果当前没有事务则抛出异常REQUIRES_NEW 创建一个新的事务。如果当前存在事务, 则把当前事务挂起。也就是说不管外部方法是否开启事务总是开启新的事务, 且开启的事务相互独立, 互不干扰NOT_SUPPORTED 以非事务方式运行。如果当前存在事务则把当前事务挂起(不用)NEVER 以非事务方式运行。如果当前存在事务则抛出异常事务补偿机制当事务成功或者失败时执行一些逻辑1. 成功补偿this.bean.database.current.commit(async () {// do something when success});2. 失败补偿this.bean.database.current.compensate(async () {// do something when failed});事务与Cache数据一致性许多框架使用最简短的用例来证明是否高性能而忽略了业务复杂性带来的性能挑战。随着业务的增长和变更项目性能就会断崖式下降各种优化补救方案让项目代码繁杂冗长。而 Vona 正视大型业务的复杂性从框架核心引入缓存策略并实现了二级缓存、Query缓存和Entity缓存等机制轻松应对大型业务系统的开发可以始终保持代码的优雅和直观Vona 系统对数据库事务与缓存进行了适配当数据库事务失败时会自动执行缓存的补偿操作从而让数据库数据与缓存数据始终保持一致针对这个场景Vona 提供了内置的解决方案1. 使用当前数据源class ServicePost {Database.transaction()async transaction() {// insertconst post await this.scope.model.post.insert({title: Post001,});// cacheawait this.scope.cacheRedis.post.set(post, post.id);}}当新建数据后将数据放入 redis 缓存中。如果这个事务出现异常就会进行数据回滚同时缓存数据也会回滚从而让数据库数据与缓存数据保持一致2. 使用指定数据源class ServicePost {async transactionManually() {const db this.bean.database.getDb({ clientName: default });await db.transaction.begin(async () {const modelPost this.scope.model.post.newInstance(db);const post await modelPost.insert({ title: Post001 });await this.scope.cacheRedis.post.set(post, post.id, { db });});}}