第一步,在主配置文件添加@EnableAsync 开启异步
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
@MapperScan({"com.example.hn.service.product.dao"})
public class HnApplication {
public static void main(String[] args) {
SpringApplication.run(HnApplication.class, args);
}
}
第二步,配置线程config
package com.example.hn.config;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncTaskConfig implements AsyncConfigurer {
@Override
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(10);
threadPool.setMaxPoolSize(100);
threadPool.setQueueCapacity(10);
threadPool.setWaitForTasksToCompleteOnShutdown(true);
threadPool.setAwaitTerminationSeconds(60);
threadPool.setThreadNamePrefix("Derry-Async-");
threadPool.initialize();
return threadPool;
}
}
第三步service实现类方法上添加注解@Async
package com.example.hn.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class TestAsyncService {
@Async
public void testAsyncTask(int i) {
System.out.println("线程" + Thread.currentThread().getName() + " 执行任务:" + i);
}
}
第四步,相关业务
package com.example.hn.service.rest;
import com.example.hn.service.GoodsService;
import com.example.hn.service.TestAsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("thread")
public class SpringbootLearnApplicationTests {
@Autowired
private TestAsyncService testAsyncService;
@GetMapping("/test")
public void threadTest() {
for (int i = 1; i <= 2; i++) {
long startTime = System.currentTimeMillis();
testAsyncService.testAsyncTask(i);
long endTime = System.currentTimeMillis();
System.out.println("第"+i+"次执行耗时:" + (endTime - startTime));
}
}
}