加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 在Slick交易中拥有自己的东西

发布时间:2020-12-16 18:14:23 所属栏目:安全 来源:网络整理
导读:我正在使用Slick 3.1.1,我想在Slick事务上实现自己的东西. def findSomeProducts = table.getSomeProducts() //db operationdef productTableUpdate = doSomeStuff1() //db operationdef priceTableUpdate = doSomeStuff2() //db operationdef updateElastic
我正在使用Slick 3.1.1,我想在Slick事务上实现自己的东西.

def findSomeProducts = table.getSomeProducts() //db operation
def productTableUpdate = doSomeStuff1() //db operation
def priceTableUpdate = doSomeStuff2() //db operation

def updateElasticCache = updateIndexOfProduct() //this is not a database operation

我有这些示例函数.首先,我正在从db中获取一些产品,并在我更新表之后.最后我需要运行updateElasticCache方法.如果updateElasticCache方法失败,我想回滚整个db procceses.

我不能用
(对于{…} yield()).事务上这个代码因为它不适用于我的情况.这个“事务性”正在等待数据库操作.但我想添加另一个不是db-process的功能.

可能吗?我怎样才能实现它?

解决方法

DBIO.from

是的!!!可以使用DBIO操作组合和DBIO.from在浮点数逻辑之间添加非db逻辑

请注意,“您自己的东西”应该返回未来,将来可以转换为DBIO,并且可以与通常的db操作一起组合.

DBIO.from可以帮助您解决这个问题.下面是它的工作原理. DBIO.from采用未来并将其转换为DBIOAction.现在,您可以使用常规数据库操作组合这些操作,以便在事务中执行非数据操作以及数据库操作.

def updateElasticCache: Future[Unit] = Future(doSomething())

现在假设我们有一些数据库操作

def createUser(user: User): DBIO[Int] = ???

如果更新缓存失败,我希望createUser回滚.所以我做了以下几点

val action = createUser.flatMap { _ => DBIO.from(updateElasticCache()) }.transactionally
db.run(action)

现在如果updateElasticCache失败,整个tx将失败,一切都将回滚到正常状态.

您可以使用理解来使其看起来很好

def updateStats: DBIO[Int] = ???
val rollbackActions =
  (for {
     cStatus <- createUser()
     uStatus <- updateStats()
     result <- DBIO.from(updateElasticCache())
   } yield result).transactionally
 db.run(rollbackActions)

如果updateElasticCache future失败,那么所有内容都会回滚

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读