Reputation: 35
I have a spring mvc web-application . It makes the following:
1.Users submit bulk order.
2.Go to success page immediately.
3.send email and sms to user and admin (separate email for each order)
I wish to run step 3 as background process So, how I can do this with spring mvc framework?which is the best technology for this?Thank You in Advance!
Upvotes: 1
Views: 1719
Reputation: 120771
The most easy way is to use Spring's @Async
support.
Example:
@Service
public class EmailAndSmsService {
@Async
public void emailAndSmsService(YourMessage message) {
//this code runs in an new thread (when Async is enabled).
//do suff
}
}
The important point is that you MUST invoke the @Async
annotated class from an OHTER bean. (If you invoke it from the same bean (this.emailAndSmsService(...)
) then spring can not apply its Async-functionalaty. (You could use real AspectJ compile or loadtime waving to overcome this problem, but this is not the scope of this answer.)
usage
@Controller
public class Controller {
@Autowired
private EmailAndSmsService emailAndSmsService;
@RequestMapping
public ModelAndView yourControllerMethod(...) {
...
emailAndSmsService(message);
}
}
Config:
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
@See Spring Reference chapter 33.4.3 The @Async Annotation for more details. Also read the complete Chapter 33.4 Annotation Support for Scheduling and Asynchronous Execution to learn how to enable @Async
-support.
An other way to solve the problem would be implementing some queue, where the controller store the messages that should been send, and have a @Scheduled
annotated method that send the messages that are in this queue.
Upvotes: 2