Как именно работают Play Framework 2.0 контроллеры / Async?
Я недавно перешел на Play Framework 2.0, и у меня есть несколько вопросов относительно того, как контроллеры действительно работают в игре.
В игровых документах упоминаются:
Из-за того, что Play 2.0 работает, код действия должен быть максимально быстрым (т. Е. Неблокирующим).
Однако в другой части документов:
/actions {
router = round-robin
nr-of-instances = 24
}
а также
actions-dispatcher = {
fork-join-executor {
parallelism-factor = 1.0
parallelism-max = 24
}
}
Кажется, что для обработки контроллеров выделено 24 актера. Я предполагаю, что каждый запрос выделяет одного из этих участников на весь срок действия запроса. Это правильно?
Кроме того, что делает parallelism-factor
значит и как fork-join-executor
отличаться от thread-pool
?
Также - документы должны сказать, что Async должен использоваться для длинных вычислений. Что квалифицируется как длинный расчет? 100мс? 300мс? 5 секунд? 10 секунд? Мое предположение будет что-нибудь за секунду, но как это определить?
Причина этого вопроса заключается в том, что тестирование вызовов асинхронного контроллера намного сложнее, чем обычных вызовов. Вы должны раскрутить поддельное приложение и выполнить полноценный запрос, а не просто вызывать метод и проверять его возвращаемое значение.
Даже если бы это было не так, я сомневаюсь, что завернуть все в Async
а также Akka.future
это путь.
Я просил об этом на IRC-канале #playframework, но ответа не было, и кажется, что я не единственный, кто не уверен, как это сделать.
Просто чтобы повторить:
- Правильно ли, что каждый запрос выделяет одного участника из пула /actions?
- Что значит
parallelism-factor
значит а почему это 1? - Как
fork-join-executor
отличаться отthread-pool-executor
? - Как долго должен рассчитываться счет
Async
? - Разве невозможно протестировать метод асинхронного контроллера без раскрутки поддельных приложений?
Заранее спасибо.
Редактировать: некоторые вещи из IRC
Некоторые вещи из IRC.
<imeredith> arturaz: i cant be boethered writing up a full reply but here are key points
<imeredith> arturaz: i believe that some type of CPS goes on with async stuff which frees up request threads
<arturaz> CPS?
<imeredith> continuations
<imeredith> when the future is finished, or timedout, it then resumes the request
<imeredith> and returns data
<imeredith> arturaz: as for testing, you can do .await on the future and it will block until the data is ready
<imeredith> (i believe)
<imeredith> arturaz: as for "long" and parallelism - the longer you hold a request thread, the more parrellism you need
<imeredith> arturaz: ie servlets typically need a lot of threads because you have to hold the request thread open for a longer time then if you are using play async
<imeredith> "Is it right that every request allocates one actor from /actions pool?" - yes i belive so
<imeredith> "What does parallelism-factor mean and why is it 1?" - im guessing this is how many actors there are in the pool?
<imeredith> or not
<imeredith> "How does fork-join-executor differ from thread-pool-executor?" -no idea
<imeredith> "How long should a calculation be to become wrapped in Async?" - i think that is the same as asking "how long is a piece of string"
<imeredith> "Is is not possible to test async controller method without spinning up fake applications?" i think you should be able to get the result
<viktorklang> imeredith: A good idea is to read the documentation: http://doc.akka.io/docs/akka/2.0.3/general/configuration.html ( which says parallelism-factor is: # Parallelism (threads) ... ceil(available processors * factor))
<arturaz> viktorklang, don't get me wrong, but that's the problem - this is not documentation, it's a reminder to yourself.
<arturaz> I have absolutely no idea what that should mean
<viktorklang> arturaz: It's the number of processors available multiplied with the factor you give, and then rounded up using "ceil". I don't know how it could be more clear.
<arturaz> viktorklang, how about: This factor is used in calculation `ceil(number of processors * factor)` which describes how big is a thread pool given for your actors.
<viktorklang> arturaz: But that is not strictly true since the size is also guarded by your min and max values
<arturaz> then why is it there? :)
<viktorklang> arturaz: Parallelism (threads) ... ceil(available processors * factor) could be expanded by adding a big of conversational fluff: Parallelism ( in other words: number of threads), it is calculated using the given factor as: ceil(available processors * factor)
<viktorklang> arturaz: Because your program might not work with a parallelism less than X and you don't want to use more threads than X (i.e if you have a 48 core box and you have 4.0 as factor that'll be a crapload of threads)
<viktorklang> arturaz: I.e. scheduling overhead gives diminishing returns, especially if ctz switching is across physical slots.
<viktorklang> arturaz: Changing thread pool sizes will always require you to have at least basic understanding on Threads and thread scheduling
<viktorklang> arturaz: makes sense?
<arturaz> yes
<arturaz> and thank you
<arturaz> I'll add this to my question, but this kind of knowledge would be awesome docs ;)
2 ответа
Когда на актера поступает сообщение актера, он удерживается на этом актере столько времени, сколько требуется для его обработки. Если вы обрабатываете запрос синхронно (вычисляете весь ответ во время обработки этого сообщения), то этот субъект не сможет обслуживать другие запросы, пока ответ не будет выполнен. Если вместо этого вы можете, после получения этого запроса, отправить работу другому субъекту, субъект, получивший запрос, может начать работу над следующим запросом, пока первый запрос обрабатывается другими участниками.
Число потоков, используемых для актеров, равно "num cpus * параллелизм-фактор" (однако вы можете указать min и max)
Не знаю
Если не будет реальных вычислений, я буду склонен выполнять асинхронизацию всего, что взаимодействует с какой-либо другой системой, например, выполнять io с базой данных / файловой системой. Конечно, все, что может заблокировать поток. Тем не менее, поскольку при передаче сообщений очень мало накладных расходов, я не думаю, что возникнет проблема с отправкой всей работы другим актерам.
См. Документацию Play по функциональным тестам о том, как тестировать свои контроллеры.
Кажется, что вы можете сделать это для тестирования:
object ControllerHelpers {
class ResultExtensions(result: Result) {
/**
* Retrieve Promise[Result] from AsyncResult
* @return
*/
def asyncResult = result match {
case async: AsyncResult => async.result
case _ => throw new IllegalArgumentException(
"%s of type %s is not AsyncResult!".format(result, result.getClass)
)
}
/**
* Block until result is available.
*
* @return
*/
def await = asyncResult.await
/**
* Block until result is available.
*
* @param timeout
* @return
*/
def await(timeout: Long) = asyncResult.await(timeout)
/**
* Block for max 5 seconds to retrieve result.
* @return
*/
def get = await.get
}
}
implicit def extendResult(result: Result) =
new ControllerHelpers.ResultExtensions(result)
val result = c.postcodeTimesCsv()(request(params)).get
status(result) should be === OK