In Spring, an allocated amount of memory is allocated for request processing. If you are running a long operation (such as uploading a large file, batch mailing, big data analysis), the memory for that request would be blocked until the operation is finished.
A better way of approaching this would be to return the request right away and let the long operation to run in another thread.
In Spring 3.x, it is relatively easy with the @Async support.
Before I dive down into the tutorial, here's my specs:
- ubuntu 12.04
- large EC2 instance
- OpenJDK 1.7
- Maven 3.0.4
- Spring 3.2.4
- CXFServlet 2.5.3 with JAX-RS (This is for Rest API)
This post will be about how to enable @Async in your spring project.
Install the latest version of Spring
At the time of this writing, the stable version is 3.2.4. The following shows how to add the maven dependency in pom.xml
Use Serlvet 3.0 namespace
In web.xml, make sure you use the XML nameplace for version 3.0.
Add Async Support in entry servlets in web.xml
If you are writing a normal Spring MVC Web app, you will need to add async-supported in the dispatcher serlvet below. My project only uses the Rest API, so I put the async-supported xml tag in the CXFServlet.
Enable Async in application context
In applicationContext.xml, enable executor and scheduler. If you don't know where is the applicationContext.xml, find it from web.xml's contextConfigLocation context-param field.
Make sure you have the task namespace as above.
Annotate a method as @Async
Below is a quick test of the @Async method. Notice the @Async annotation below.
Try taking out the @Async annotation and execute the program. You should be able to observe the difference.
Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I'll be sure to check back again real soon.
ReplyDeleteMinecraft Server List
Intresting information app spring java i love iot and wants to get more info about it
ReplyDelete