table of Contents
1, based on the timing task Timer
2, a timing based on the task ScheduledExecutorService
2.4 thread exception print log
3.1 thread pool configuration class
1, based on the timing task Timer
1.1 Introduction
Before using JDK1.5 are Timer timer to complete the task, and there is a single thread to perform regular tasks , and therefore the following problems:
- The interaction between multiple tasks (as long as one does not catch the exception, other tasks will automatically terminate)
- Multi-tasking is serial, inefficient
1.2 Examples
POST request sent using PostMan: localhost: 8888 / ruoyi / login, request parameters: user name, password, authentication code, UUID
Controller layer receives the request, and process the request calls the service layer
Task start timing of two layers sercie
A task is delayed three seconds to print user name, password, authentication code and thread name and uuid
Another task is delayed 1 second intervals of 1 second print time and the current thread name
1.3 front end request
1.4 Controller layer
package com.ruoyi.project.system.controller;
/**
* 登录验证
*
* @author ruoyi
*/
@RestController
public class SysLoginController {
@Resource
private SysLoginService loginService;
@PostMapping("/login")
public AjaxResult login(String username, String password, String code, String uuid) {
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(username, password, code, uuid);
ajax.put(Constants.TOKEN, token);
return ajax;
}
}
1.5 Service Layer
1.6 results
2, a timing based on the task ScheduledExecutorService
2.1 Introduction
ScheduledExecutorService is JDK1.5 appear, based on multi-threaded, independently of each other between the threads
2.2 Examples
In the previous example, we found that the timer task accomplished by timer, as long as there is an exception occurs while a task is not handled, other tasks will be terminated! !
This example will solve this problem.
2.3 Service Layer
Controller requests and distal layers of the same code is not repeated here
2.4 thread exception print log
package com.ruoyi.common.utils;
/**
* 线程相关工具类.
*
* @author ruoyi
*/
public class Threads {
private static final Logger logger = LoggerFactory.getLogger(Threads.class);
/**
* 打印线程异常信息
*/
public static void printException(Runnable r, Throwable t) {
if (t == null && r instanceof Future<?>) {
try {
Future<?> future = (Future<?>) r;
if (future.isDone()) {
future.get();
}
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
if (t != null) {
logger.error(t.getMessage(), t);
}
}
}
2.5 operating results
3, to improve
On a case ScheduledExecutorService new objects are out, this is not good coding!
①, ScheduledExecutorService objects should be completed by the Spring container management.
②, should ScheduledExecutorService encapsulates asynchronous task manager to make a single embodiment of
3.1 thread pool configuration class
The configuration class, the object is injected into the Spring container ScheduledExecutorService
package com.ruoyi.framework.config;
/**
* 线程池配置
*
* @author ruoyi
**/
@Configuration
public class ThreadPoolConfig {
// 核心线程池大小
private int corePoolSize = 50;
/**
* 执行周期性或定时任务
*/
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() {
return new ScheduledThreadPoolExecutor(corePoolSize,
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
Threads.printException(r, t);
}
};
}
}
3.2 Asynchronous Task Manager
package com.ruoyi.framework.manager;
/**
* 异步任务管理器
*
* @author ruoyi
*/
public class AsyncManager {
/**
* 操作延迟10毫秒
*/
private final int OPERATE_DELAY_TIME = 10;
/**
* 异步操作任务调度线程池
*/
private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
/**
* 单例模式
*/
private AsyncManager() {
}
private static AsyncManager me = new AsyncManager();
public static AsyncManager me() {
return me;
}
/**
* 执行任务
*
* @param task 任务
*/
public void execute(TimerTask task) {
executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
}
}
3.3 Service Layer
Controller code unchanged and the distal layer
3.4 operating results