EJB 3.1和NIO2:监视文件系统 [英] EJB 3.1 and NIO2: Monitoring the file system
问题描述
我想我们大多数人都同意,使用NIO2是一件好事.假设您要监视文件系统的某些部分是否有传入的xml-文件,这是一件容易的事.但是,如果我想将这些东西集成到现有的Java EE应用程序中,而不必启动另一项服务(应用服务器 AND 监视文件系统的服务)怎么办? 因此,我拥有重量级的app-server,其中包含所有EJB 3.1内容以及某种监视文件系统的服务,并在文件显示后采取适当的措施.有趣的是,适当的操作是创建一条消息,然后通过JMS发送该消息,最好将两者都集成到应用服务器中.
I guess most of us agree, that NIO2 is a fine thing to make use of. Presumed you want to monitor some part of the file system for incoming xml - files it is an easy task now. But what if I want to integrate the things into an existing Java EE application so I don't have to start another service (app-server AND the one which monitors the file system)? So I have the heavy weight app-server with all the EJB 3.1 stuff and some kind of service monitoring the file system and take appropriate action once a file shows up. Interestingly the appropriate action is to create a Message and send it by JMS and it might be nice to integrate both into the app server.
我尝试了@Startup,但是部署冻结了(我知道我不应该在其中使用I/O,只是尝试一下).无论如何...有什么建议吗?
I tried @Startup but deployment freezes (and I know that I shouldn't make use of I/O in there, was just a try). Anyhow ... any suggestions?
推荐答案
您可以创建一个在启动时加载并将监视委托给异步bean的单例
You could create a singleton that loads at startup and delegates the monitoring to an Asynchronous bean
@Singleton
@Startup
public class Initialiser {
@EJB
private FileSystemMonitor fileSystemMonitor;
@PostConstruct
public void init() {
String fileSystemPath = ....;
fileSystemMonitor.poll(fileSystemPath);
}
}
然后,异步bean看起来像这样
Then the Asynchronous bean looks something like this
@Stateless
public class FileSystemMonitor {
@Asynchronous
public void poll(String fileSystemPath) {
WatchService watcher = ....;
for (;;) {
WatchKey key = null;
try {
key = watcher.take();
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue; // If events are lost or discarded
}
WatchEvent<Path> watchEvent = (WatchEvent<Path>)event;
//Process files....
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
} finally {
if (key != null) {
boolean valid = key.reset();
if (!valid) break; // If the key is no longer valid, the directory is inaccessible so exit the loop.
}
}
}
}
}
这篇关于EJB 3.1和NIO2:监视文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!