我正在编写一个Spring-Boot应用程序来监视目录并处理正在添加到其中的文件 . 我通过在 Application 类中创建一个ApplicationRunner来启动一个线程,该类调用一个用 @Async 注释的方法:
@SpringBootApplication
@EnableAsync
public class Application {
@Autowired
private DirectoryMonitorService directoryMonitorService;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public ApplicationRunner startDirectoryMonitorService() {
return args -> directoryMonitorService.monitorSourceDirectoty();
}
}
以下是 DirectoryMonitorService 的代码,其中包含使用 @Async 注释的方法:
@Service
public class DirectoryMonitorService {
private static final Logger logger = LogManager.getLogger(DirectoryMonitorService.class);
@Value("${timeout}")
private long timeout;
@Autowired
private WatchService watchService;
@Async
public void monitorSourceDirectoty() {
while (true) {
WatchKey watchKey;
try {
watchKey = watchService.poll(timeout, TimeUnit.SECONDS);
} catch (ClosedWatchServiceException | InterruptedException e) {
logger.error("Exception occured while polling from source file", e);
return;
}
// process the WatchEvents
if (!watchKey.reset()) {
break;
}
}
}
}
public class AsyncConfig extends AsyncConfigurerSupport {
private static final Logger logger = LogManager.getLogger(AsyncConfig.class);
private static final String THREAD_NAME_PREFIX = "Parser-";
@Value("${corePoolSize}")
public int corePoolSize;
@Value("${maxPoolSize}")
public int maxPoolSize;
@Value("${queueCapacity}")
public int queueCapacity;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (Throwable ex, Method method, Object... params) -> {
logger.error("Exception message - " + ex.getMessage());
logger.error("Method name - " + method.getName());
for (Object param : params) {
logger.error("Parameter value - " + param);
}
};
}
}
不知怎的,我觉得这不是启动主线程最优雅的方式 . 有人有更好的解决方案吗?
另外,我宁愿将 while (true) 替换为 Boolean 变量,当Spring-Boot关闭时,我可以将其设置为false . 有谁知道我需要为此实现哪个接口?