LingxinMeng %!s(int64=2) %!d(string=hai) anos
pai
achega
12ec8d306b

+ 40 - 0
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/configuration/async/AsyncConfiguration.java

@@ -0,0 +1,40 @@
+package com.css.simulation.resource.scheduler.configuration.async;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+import java.util.concurrent.ThreadPoolExecutor;
+
+@Data
+@EnableAsync
+@Configuration
+@ConfigurationProperties(prefix = "thread-pool")
+public class AsyncConfiguration {
+    private String threadNamePrefix;    // 名称前缀
+    private int corePoolSize;   // 核心线程数
+    private int maxPoolSize;    // 最大线程数
+    private int queueCapacity;  // 队列大小
+
+    /**
+     * 在方法上使用 @Async("pool-default")
+     */
+    @Bean(name = "pool-default")
+    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
+        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
+        threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
+        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
+        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
+        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
+        threadPoolTaskExecutor.setKeepAliveSeconds(3);
+        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
+        // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
+        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
+        // 加载
+        threadPoolTaskExecutor.initialize();
+        return threadPoolTaskExecutor;
+    }
+}

+ 2 - 2
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/service/TaskService.java

@@ -7,8 +7,8 @@ import com.css.simulation.resource.scheduler.data.entity.TaskEntity;
 import com.css.simulation.resource.scheduler.mapper.TaskMapper;
 import com.css.simulation.resource.scheduler.util.ProjectUtil;
 import com.css.simulation.resource.scheduler.util.TaskUtil;
-import lombok.SneakyThrows;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
@@ -28,7 +28,7 @@ public class TaskService {
 
     // -------------------------------- Comment --------------------------------
 
-    @SneakyThrows
+    @Async("pool-default")
     public void state(String taskId, String state, String podName) {
         TaskEntity taskEntity = taskMapper.selectById(taskId);
         String projectId = taskEntity.getPId(); // 项目 id