2015-10-20 55 views
0

我正在開發一個使用Spring 4.1.6和Mongodb的應用程序。我想在fire and forget模式中執行一些任務,例如一旦訪問了一個方法,將會創建一個集合中的一個條目。我不想等到收集完成或者如果失敗,我也不需要任何通知。如何使用Spring實現這一點。春季背景/火與遺忘處理

回答

5

你可以做到這一點,沒有春天,但與春天我建議使用@Async

首先你需要啓用它。這樣做對配置類:

@Configuration 
@EnableAsync 
public class AppConfig { 
} 

然後在bean中使用@Async你想得太執行異步

@Component 
public class MyComponent { 
    @Async 
    void doSomething() { 
     // this will be executed asynchronously 
    } 
} 

你的方法可以有參數的方法:

@Component 
public class MyComponent { 
    @Async 
    void doSomething(String s, int i, long l, Object o) { 
     // this will be executed asynchronously 
    } 
} 

在你的情況下,你不需要它,但方法可以返回一個未來:

@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"); 
    } 
} 
+0

我嘗試過使用異步,但執行並不火併且忘記。它等待Async方法完成執行。我想要火,忘記執行的類型。 – Debopam

+0

@Debopam,它應該使用'@ Async',你正確使用它嗎?我們可以在問題中看到一些代碼嗎? – ESala

+2

對不起,我錯過了配置中的@EnableAsync。它正在工作。 – Debopam