1. 程式人生 > 其它 >Java中使用執行緒時,請不要忘記Spring TaskExecutor元件

Java中使用執行緒時,請不要忘記Spring TaskExecutor元件

當我們實現的web應用程式需要長時間執行一個任務時,Spring TaskExecutor管理元件是一個很好選擇,會給我們程式碼的實現提供很大的方便,也會節省時間和成本,程式的效能相信也有一個提升。

在web應用程式中使用執行緒是比較常見的實現,特別是需要長時間執行一個任務時,必須使用執行緒實現。

網路配圖

Spring提供了TaskExecutor作為抽象處理執行人。

通過提供Spring TaskExecutor的實現,你將能夠注入TaskExecutor類和訪問託管執行緒。

package com.gkatzioura.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AsynchronousService {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private TaskExecutor taskExecutor;
public void executeAsynchronously() {
taskExecutor.execute(new Runnable() {
@Override
public void run() {
//TODO add long running task
}
});
}
}

第一步是Spring應用程式新增TaskExecutor配置

package com.gkatzioura.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
public class ThreadConfig {
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(4);
executor.setThreadNamePrefix("default_task_executor_thread");
executor.initialize();
return executor;
}
}

我們提供執行人設定,這個過程很簡單,我們注入執行人,然後我們提交要執行任務執行的類。

因為我們的非同步程式碼可能需要與其他元件的互動應用程式和注射,一個不錯的方法是建立原型作用域可執行例項。

package com.gkatzioura;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class MyThread implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(MyThread.class);
@Override
public void run() {
LOGGER.info("Called from thread");
}
}

最後,注入我們服務的執行者和用它來執行可執行的例項。

package com.gkatzioura.service;
import com.gkatzioura.MyThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AsynchronousService {
@Autowired
private TaskExecutor taskExecutor;
@Autowired
private ApplicationContext applicationContext;
public void executeAsynchronously() {
MyThread myThread = applicationContext.getBean(MyThread.class);
taskExecutor.execute(myThread);
}
}