Tuesday, 15 September 2015

How do I mix synchronous and asynchronous requests in Spring MVC? -



How do I mix synchronous and asynchronous requests in Spring MVC? -

(i'm asking question intent of answering it. asked on spring forums couple of months ago, , found solution through experimentation shortly after. i'm posting here in case else hits same scenario , because told to.)

i have spring mvc endpoint /work processing io bound , can take few seconds complete. come in servlet 3 asynchronous requests , spring mvc asynchronous request processing. can homecoming callable<foo> or deferredresult<foo> , free servlet container threads useful while processing happening.

now it's other users create identical request. there's no point repeating work done, i'm going cache result of work first time completes, , want homecoming cached result. now, exact same handler method can take either few seconds finish or couple of milliseconds complete.

my problem can give handler method 1 signature, , i've defined returning callable<foo>. can't figure out how kill overhead short requests; stands, i'd create callable<foo>, enqueue behind long-running tasks , wait thread in thread pool hands on it, , serve response had in hand. i'd avoid this.

if utilize deferredresult<foo> instead of callable<foo>, things bit improve performance-wise, i've taken processing out of spring managed thread, lost spring security's securitycontext, , have polluted non-web code spring-specific deferredresult.

is there efficient way serve responses asynchronously , serve them synchronously same mvc handler method?

the solution quite simple. if handler method returns object, spring determines result based on type. correctly triggers asynchronous processing if homecoming value callable<foo>, , returns result otherwise, avoiding asynchronous processing overhead when cached result in hand.

spring spring-mvc

No comments:

Post a Comment