I am developing an application using Spring 4.1.6 and Mongodb. I would like to perform some of the task in fire and forget mode e.g. once a method is accessed an entry in a collection will be made. I don't want to wait till writing to collection finishes or if it fails I don't need any notification either. How to achieve this using Spring.
You can do this without spring but with spring i suggest to use @Async.
First you need to enable it. To do so on a Configuration class:
@Configuration
@EnableAsync
public class AppConfig {
}
Then in a bean use @Async on the method you want to be execute asynchronously
@Component
public class MyComponent {
@Async
void doSomething() {
// this will be executed asynchronously
}
}
Your method can have parameters too:
@Component
public class MyComponent {
@Async
void doSomething(String s, int i, long l, Object o) {
// this will be executed asynchronously
}
}
In your case you don't need it but the method can return a Future:
@Component
public class MyComponent {
@Async
Future<String> doSomething(String s, int i, long l, Object o) {
// this will be executed asynchronously
return new AsyncResult<>("result");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With