欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 异步任务

程序员文章站 2022-05-01 14:18:36
...
package com.boot.mytt.core.tasks;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.task.TaskExecutorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class TaskConfig {

    @Bean
    public ThreadPoolTaskExecutor customTaskExecutor(TaskExecutorBuilder taskExecutorBuilder) {
        return taskExecutorBuilder.threadNamePrefix("customTask-")
                .corePoolSize(5).build();
    }

    @Bean
    public ThreadPoolTaskExecutor myTaskExecutor(TaskExecutorBuilder taskExecutorBuilder) {
        return taskExecutorBuilder.threadNamePrefix("myTask-")
                .corePoolSize(10).build();
    }

    @Bean
    CommandLineRunner clrTask(AsyncTask asyncTask) {
        return args -> {
            for (int k=0; k<10; k++) {
                asyncTask.loopPrint(k);
            }

            for (int k=0; k<10; k++) {
                asyncTask.loopPrint2(k);
            }
        };
    }
}
package com.boot.mytt.core.tasks;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AsyncTask {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Async("customTaskExecutor")
    public void loopPrint(Integer k) {
        log.info(Thread.currentThread().getName() + ":" + k);
    }

    @Async("myTaskExecutor")
    public void loopPrint2(Integer k) {
        log.info(Thread.currentThread().getName() + ":" + k);
    }
}



或属性配置:

book:
  name: zhangsan
  age: 22
spring:
  main:
    allow-bean-definition-overriding: true
  task:
    execution:
      pool:
        core-size: 10
        max-size: 20
      thread-name-prefix: mytask-
logging:
  level:
    org:
      springframework:
        web: DEBUG
  file:
    path: d:/logs

 

相关标签: spring boot