
本文旨在提供一种在Spring Boot应用中优雅地终止先前运行的无限循环任务并启动新任务的解决方案。通过使用线程管理和唯一ID,我们可以安全地中断正在运行的任务,并避免资源泄漏。本文将提供详细的代码示例和步骤,帮助你理解和实现该方案。
在Spring Boot应用中,有时我们需要执行一些无限循环的任务,例如日志打印、数据监控等。然而,直接使用while(true)循环可能会导致难以控制的任务,尤其是在需要停止并启动新任务时。以下提供一种使用线程管理和唯一ID来优雅地终止先前运行的任务并启动新任务的解决方案。
以下是一个Spring Boot Controller的示例代码,演示了如何实现上述思路:
package com.springbootLogging.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@RestController
@RequestMapping(path="/")
public class AppController {
private static final Logger logger = LoggerFactory.getLogger(AppController.class);
private static final Map<String, Thread> threadLookup = new ConcurrentHashMap<>();
@CrossOrigin
@GetMapping(path="/startLog")
public ResponseEntity<String> startPrintingLogs() {
UUID uuid = UUID.randomUUID();
String uuidString = uuid.toString();
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
logger.debug("It is a debug logger.");
logger.error("It is an error logger.");
logger.info("It is an info logger.");
logger.trace("It is a trace logger.");
logger.warn("It is a warn logger.");
try {
Thread.sleep(100); // 避免CPU占用过高
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重新设置中断状态
}
}
logger.info("Thread with UUID {} stopped.", uuidString);
});
thread.start();
threadLookup.put(uuidString, thread);
return ResponseEntity.ok(uuidString); // 返回UUID
}
@CrossOrigin
@GetMapping(path="/stopLog")
public ResponseEntity<String> stopPrintingLogs(String uuid) {
Thread thread = threadLookup.get(uuid);
if (thread == null) {
return ResponseEntity.notFound().build(); // 返回404
} else {
thread.interrupt();
threadLookup.remove(uuid); // 移除线程引用
return ResponseEntity.ok("Thread with UUID " + uuid + " interrupted.");
}
}
}代码解释:
通过使用线程管理和唯一ID,我们可以优雅地终止Spring Boot中的无限循环任务,并避免资源泄漏。这种方法具有良好的可扩展性和可维护性,适用于各种需要执行无限循环任务的场景。希望本文能够帮助你更好地理解和应用这种方案。
以上就是优雅地终止Spring Boot中的无限循环任务并启动新任务的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号