2017-04-21 80 views
0

我customDao如下面我springboot的應用程序,春季啓動:更新操作的新主題

@Component 
public class CustomDao { 

    private final JdbcTemplate jdbcTemplate 

    @Autowired 
    private PlatformTransactionManager transactionManager; 

    def logger = LoggerFactory.getLogger(this.class); 
    @Autowired 
    public CustomDao(JdbcTemplate template) { 
     this.jdbcTemplate = template 
    } 


    public insertRecord(sql,params){ 
     //insert 
    } 

    public updateRecord(sql,params){ 
     //update 
    } 
} 

,我試圖讓異步在一個新線程只更新操作,我沒有太多的工作線程上,可以有人請幫我這個嗎?

+1

查看[本文](http://www.baeldung.com/spring-async),瞭解您可以用Spring的'@ Async'註釋做些什麼。 – zloster

回答

1

您可以修改updateRecord方法是:

public void updateRecord(sql, params) { 
    Thread t = new Thread() { 
     //Your code to update here 
    } 
    t.start(); 
} 

Thread t = new Thread() {...}將創建一個新的線程來完成指定的工作,並t.start()會在後臺運行的線程。

+1

但他也需要來自原始線程的'ThreadLocal's。 Spring在那裏存儲一些重要的東西。另外最好使用某種形式的線程池。目前的做法很快就會變得「昂貴」。 – zloster

+0

@zloster可以請你提供你的答案與線程池和ThreadLocals – RanPaul

+0

@RanPaun請參閱[本答案](http://stackoverflow.com/a/33337838/25429)爲'ThreadLocal's - 取決於代碼基礎可能會或可能不需要它們。關於ThreadPool:你指定['@Async(「customThreadPoolExecutor」)'](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#scheduling-annotation-support-qualification )和customTHreadPoolExecutor的[定義配置](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#scheduling-task-namespace-executor)。 – zloster

1

您應該使用@Async來處理到Spring的異步任務。你可以找到一個例子here