SpringBoot asynchronous task (1) | (asynchronous task execution and callback)

SpringBoot asynchronous task (1) | (asynchronous task execution and callback)


Chapter
Chapter 1 link: SpringBoot asynchronous task (1) | (asynchronous task execution and callback)

foreword

The use of asynchronous tasks in springboot

1. Usage scenarios

There is a task to import data in the project. Importing data is time-consuming, so it is executed in an asynchronous task mode. Task execution hopes to update the task status immediately

Two, springboot adds asynchronous tasks

1. Add asynchronous tasks to the startup class

Add the @EnableAsync annotation to the startup class to enable asynchronous tasks. The @EnableAsync annotation will open a thread word when the springboot project starts. The default parameters are as follows:

	默认核心线程数:8
    最大线程数:Integet.MAX_VALUE,
    队列使用LinkedBlockingQueue,
    容量是:Integet.MAX_VALUE,
    空闲线程保留时间:60s,
    线程池拒绝策略:AbortPolicy

There are many problems and risks in the default thread pool, which can be customized

spring:
  task:
    execution:
      pool:
        max-size: 6
        core-size: 3
        keep-alive: 3s
        queue-capacity: 1000
        thread-name-prefix: name

2. Write task execution service

The task execution service provides two methods, one submits execution without response, and the second waits for the completion of task execution after submitting execution, and then updates the status

@Log4j2
@Component
public class LoadTaskExecutor {
    
    

    @Async
    public void execute(LoadTask task) {
    
    
        log.info("LoadTask is executing run task:{}", task.getId());
        task.run();
    }

    @Async
    public void execute(LoadTask task, Runnable callback) {
    
    
        synchronized (task.getGraphName()) {
    
    
            log.info("Executing task: {}", task.getId());
            task.run();
            log.info("Executed task: {}, update status to db", task.getId());
            callback.run();
        }
    }
}

LoadTask class example

@Log4j2
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class LoadTask implements Runnable {
    
    

    private String id;
    private String graphName;
    private String jobId;
    private String fileId;



    public LoadTask(LoadOptions options, GraphConnection connection,
                    FileMapping mapping) {
    
    
        this.id = null;
        this.graphName = StringUtils.isEmpty(connection.getGraph()) ? mapping.getGraphName() : connection.getGraph();
        this.jobId = mapping.getJobId();
        this.fileId = mapping.getId();
        this.fileName = mapping.getName();
    }

    /**
     * 运行任务
     */
    @Override
    public void run() {
    
    
        //运行任务业务代码
        log.info("映射任务运行完成:{}", this.id);
    }
}

3. Task scheduling method

1. The way springboot calls tasks

 public LoadTask start(GraphConnection connection, FileMapping fileMapping) {
    
    
        // 数据初始化以及准备工作 ...
        //调用任务
        this.taskExecutor.execute(task, () -> {
    
    
            try {
    
    
                this.updateStatus(task);
            } catch (Exception e) {
    
    
                log.error("任务执行完成更新任务状态异常:{}", e.getMessage());
            }
        });
        this.runningTaskContainer.put(task.getId(), task);
        return task;
    }

Summarize

The above method implements the idea of ​​asynchronous multi-threaded execution. You can refer to this mode and use it in design scenarios

Guess you like

Origin blog.csdn.net/Oaklkm/article/details/129045938