@LastModifiedBy在协程内部不起作用

时间:2020-05-18 16:08:01

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

在我的应用程序中,我使用 trait A case class B() extends A case class C() extends A def someMethod(o: Option[A]): Double = { o.map(v => { case B => 1.3 case C => 1.2 case others => 2.3 }).getOrElse(0.0) // Expression of type Any doesn't conform to expected type Double > } ,并且它在完美运行之前,直到我决定使用协同例程来提高性能。

现在,由于对我的存储库的调用位于Future内并且在协程中执行,因此标记为@LastModifiedBy@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 ")
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我设法做到这一点:

@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提供的链接!