【问题标题】:@LastModifiedBy doesn't work inside coroutine@LastModifiedBy 在协程中不起作用
【发布时间】:2020-09-04 12:14:00
【问题描述】:

在我的应用程序中,我使用了@LastModifiedBy,它运行良好,直到我决定使用协程进行表演。

现在,由于对我的存储库的调用在 Future 中并在协程中执行,标记为 @LastModifiedBy@LastModifiedDate 的字段在持久化时不再填充。

当我在执行到协程中的代码中进行调试并停止时,SecurityContextHolder 是空的,而它在协程之外被填充。

我的代码是这样的:

@RestController
class Controller( val service : MyService){
( ... )

    @PutMapping(...)
        fun saveStuff( val allStuff : List<Stuff>) : String{
         return service.saveStuff(allStuff )
    }

}

对于协程而言:

@Service
class MyService( val repo: MyRepository){

    fun saveStuff( allStuff: List<Stuff>){
        val deferred: List<Deferred<Unit>> =
            allStuff.forEach{
                  GlobalScope.async {  repo.save(stuff)}
            }

        runBlocking {
            val count = deferred.map { it.await() }.count()
            log.info(" all the $count future(s) have finish ")
        }
    }
}
@Entity
data class Stuff(
     @CreatedDate
     var creationDate: Timestamp? = null,

     @LastModifiedBy
     var lastModificationBy: String? = null,

     @LastModifiedDate
     var lastModificationDate: Timestamp? = null
)

【问题讨论】:

标签: kotlin spring-data-jpa kotlin-coroutines


【解决方案1】:

我设法做到了:

@Service
class MyService( val repo: MyRepository){
    fun saveStuff( allStuff: List<Stuff>){
        val deferred: List<Deferred<Unit>> =
            allStuff.forEach{
              GlobalScope.async {  repo.save(stuff)}
        }

        val threadLocal = ThreadLocal<SecurityContext>() // declare thread-local variable
        //pass security context to all thread which will execute my code
        GlobalScope.launch(Dispatchers.Default + threadLocal.asContextElement(SecurityContextHolder.getContext())) {
            //set up context for spring
            SecurityContextHolder.setContext(threadLocal.get())
            val count = deferred.map { it.await() }.count()
            log.info(" all the $count future(s) have finish ")
        }
    }
}

它就像一个魅力:) 感谢@sidgate 的链接!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2021-03-07
    • 2015-08-06
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 2022-07-14
    相关资源
    最近更新 更多