spring boot 异步任务

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

猜你喜欢

转载自blog.csdn.net/qq_37769323/article/details/105892130