JavaEE开发的颠覆者:Spring Boot实战 学习笔记4--Spring高级话题

SpringAware 

可调用Spring所提供的资源

 多线程

配置类

/**
 * 多线程和并发编程
 */
@Configuration
@ComponentScan("com.wisely.highlight_spring4_idea.ch3.taskexecutor")
@EnableAsync //开启异步任务支持
//实现AsyncConfigurer接口,重写getAsyncExecutor方法返回一个ThreadPoolTaskExecutor
public class TaskExecutorConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {//获得基于线程池TaskExecutor
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

Service 注解Async 

@Service
public class AsyncTaskService {
    @Async //注解声明这是个异步方法,若注解在类级别,则表明该类的方法都是异步方法
            //而这里的方法都自动被注入使用ThreadPoolTaskExecutor作为TaskExecutor
    public void executeAsyncTask(Integer i){
        System.out.println("异步任务1:"+i);
    }
    @Async
    public void executeAsyncPlus(Integer i){
        System.out.println("异步任务2:"+(i+1));
    }
}

计划任务

@EnableScheduling//开启对计划任务的支持

@Scheduled(fixedRate = 5000)//计划任务 每隔5s执行一次

@Scheduled(cron = "0 * * * * *")//指定事件执行 参照https://blog.csdn.net/love3765/article/details/78655581

 

猜你喜欢

转载自blog.csdn.net/huofuman960209/article/details/82969847