目錄
1.使用java配置定義線程池和啓用異步
package com.lin.demo.config;
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;
/**
* 使用Java配置定義線程池和啓用異步
* */
@Configuration
/**開異步可用*/
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
/**定義線程池*/
@Override
public Executor getAsyncExecutor() {
//定義線程池
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//核心線程數
taskExecutor.setCorePoolSize(10);
//線程池最大線程數
taskExecutor.setMaxPoolSize(30);
//線程隊列最大線程數
taskExecutor.setQueueCapacity(2000);
//初始化
taskExecutor.initialize();
return taskExecutor;
}
}
2.異步服務接口
package com.lin.demo.service;
/**
* 異步服務接口
* */
public interface AsyncService {
/**
* 模擬報表生成的異步方法
*/
void generateReport();
}
3.異步服務接口實現類
package com.lin.demo.service.impl;
import com.lin.demo.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* 異步服務實現類
* */
@Service
public class AsyncServiceImpl implements AsyncService {
@Override
/**聲明使用異步調用*/
@Async
public void generateReport() {
//打印異步線程名稱
System.out.println("報表線程名稱:" + "【" + Thread.currentThread().getName() + "】");
}
}
4.控制層調用
package com.lin.demo.controller;
import com.lin.demo.service.AsyncService;
import org.springframework.stereotype.Controller;
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;
/**
* 控制器
* */
@RestController
public class AsyncController {
@Resource
private AsyncService asyncService;
@GetMapping("/async/page")
public String asyncPage() {
System.out.println("請求線程名稱:" + "【" + Thread.currentThread().getName() + "】");
//調用異步服務
asyncService.generateReport();
return "async";
}
}