Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Background / Fire and Forget processing

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.

like image 823
Debopam Avatar asked Jun 13 '26 14:06

Debopam


1 Answers

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");
    }
}
like image 83
JEY Avatar answered Jun 16 '26 02:06

JEY