package com.aosiding;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Resource
private Environment env;
@Bean("taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setThreadNamePrefix("--------------全局线程池-----------------");
System.out.println(("--------------全局线程池-----------------"));
pool.setCorePoolSize(Integer.parseInt(env.getProperty("threadpool.corePoolSize")));
pool.setMaxPoolSize(Integer.parseInt(env.getProperty("threadpool.maxPoolSize")));
pool.setKeepAliveSeconds(Integer.parseInt(env.getProperty("threadpool.queueCapacity")));
pool.setQueueCapacity(Integer.parseInt(env.getProperty("threadpool.keepAliveSeconds")));
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
pool.initialize();
return pool;
}
}
package com.aosiding.controller;
import com.aosiding.AsynchronousTask;
import com.aosiding.pojo.Product;
import com.aosiding.service.ProductService;
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;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@Resource
private AsynchronousTask asynchronousTask;
@GetMapping("list")
public List<Product> selectProduuctList(){
return productService.selectProductList();
}
@GetMapping("login")
public String login(){
Long userId=10001L;
boolean isSucc=true;
if(isSucc){
asynchronousTask.recordLoginLog(userId);
}
System.out.println("=====登录成功====");
return "登录成功";
}
}
package com.aosiding;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsynchronousTask {
@Async("taskExecutor")
public void recordLoginLog(Long userId){
System.out.println("======== 登录日志记录=====start=======");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("========登录日志记录------end=======");
}
}