应如何设置 Play 应用程序以一次按顺序处理请求?
How should a Play application be set up to handle requests sequentially at a time?
假设我有一个执行外部命令的应用程序,不能运行并行,如下
Future("command_to_run".run().exitValue())
对应用程序的要求是它应该接受请求并通过执行命令顺序处理它们。处理请求的顺序不是很重要。
达到此要求的最简单或推荐的方法是什么?
您可以通过在范围内定义一个single-threaded执行上下文来实现它:
implicit val ec = ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())
如果导入了全局 EC,则需要将其删除:
import scala.concurrent.ExecutionContext.Implicits.global // to be removed
最简单的方法可能是,扩展 Feyyaz 的回答,定义一个 single-thread ExecutionContext
:
val singlethread = ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())
我建议不要隐式设置此上下文,因为您只想在该上下文中执行命令。
val execution = Future("command_to_run".run())(singleThread)
execution.map(_.exitValue) // will execute on the regular execution context in scope
单线程上下文的使用时间不会超过 运行 命令所需的时间,然后可用于为下一个请求提供服务。一般来说,拥有
并不是一个好主意
import scala.concurrent.ExecutionContext.Implicits.global
在生产代码中,除非你真的知道你在做什么(IMO,编译器认为这是一个可怕的错误)。
还值得考虑使用 Akka actor 来同步 运行 命令:这将简化失败 handling/cleanup 并且在 ExecutionContext
方面不需要任何特殊的东西,在需要使用 ActorSystem
游戏用品的费用。
假设我有一个执行外部命令的应用程序,不能运行并行,如下
Future("command_to_run".run().exitValue())
对应用程序的要求是它应该接受请求并通过执行命令顺序处理它们。处理请求的顺序不是很重要。
达到此要求的最简单或推荐的方法是什么?
您可以通过在范围内定义一个single-threaded执行上下文来实现它:
implicit val ec = ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())
如果导入了全局 EC,则需要将其删除:
import scala.concurrent.ExecutionContext.Implicits.global // to be removed
最简单的方法可能是,扩展 Feyyaz 的回答,定义一个 single-thread ExecutionContext
:
val singlethread = ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())
我建议不要隐式设置此上下文,因为您只想在该上下文中执行命令。
val execution = Future("command_to_run".run())(singleThread)
execution.map(_.exitValue) // will execute on the regular execution context in scope
单线程上下文的使用时间不会超过 运行 命令所需的时间,然后可用于为下一个请求提供服务。一般来说,拥有
并不是一个好主意import scala.concurrent.ExecutionContext.Implicits.global
在生产代码中,除非你真的知道你在做什么(IMO,编译器认为这是一个可怕的错误)。
还值得考虑使用 Akka actor 来同步 运行 命令:这将简化失败 handling/cleanup 并且在 ExecutionContext
方面不需要任何特殊的东西,在需要使用 ActorSystem
游戏用品的费用。