观察者模式适合文件监视?观察者、适合、模式、文件

2023-09-11 03:37:06 作者:领嗨红人馆

我有兴趣知道,如果观察者模式是正确的方法来实现code监视日志文件和它们的变化?

我目前正在使用它,但似乎有一种反常现象,我不能完全解释。基本上,我创建一个类FileMonitor的具有火灾,迭代访问的唯一文件列表寻找改变上次更改日期的计时器。

在找到它,听众的名单是通过迭代找到匹配的文件,它的 fileChanged事件通知。然后,它开始处理中加入的文件中的所有行。

因此​​,为了使我的问题更简洁:

是否观察者模式适合什么,我试图做? (目前 我有每个文件一个监听器) 是否有任何可能的并发问题因为有多个文件到 监测?

感谢

解决方案

如果你不想使用Java 7,你可以得到的阿帕奇IO 。

从官方文档:

  

FileAlterationObserver重新presents低于根文件的状态   目录,检查文件和通知创建的听众,   更改或删除事件。

下面是要执行如何添加监听器定义操作,当这样的事件发生。

 文件目录=新的文件(新文件(),SRC。);
  FileAlterationObserver观察者=新FileAlterationObserver(目录);
  observer.addListener(...);
  observer.addListener(...);
 
戏说模式之 观察者模式 三体

您必须注册oberver(S)与 FileAlterationMonitor 。从相同的文档继续:

 长间隔= ...
  FileAlterationMonitor显示器=新FileAlterationMonitor(区间);
  monitor.addObserver(观察员);
  monitor.start();
  ...
  monitor.stop();
 

其中,的间隔是时间量(以毫秒为单位)的文件系统检查之间的等待时间。

查找包名为 org.apache.commons.io.monitor 库。

I am interested to know if the Observer Pattern is correct approach for implementing code to monitor log files and their changes?

I am currently using it, but there seems to be an anomaly that I can't quite explain. Basically, i create a Class called FileMonitor that has a timer that fires, that iterates a list of unique files looking for a changed "lastmodified date".

Upon finding it, a list of Listeners are iterated through to find the matching file, and it's fileChanged event is notified. It then begins to process the lines that were added in the file.

So to make my question more succinct:

Does the Observer Pattern fit what I am trying to do? (Currently I have one Listener per file) Is there any possibility of 'concurrency issues' given that there is more than one File to monitor?

Thanks

解决方案

If you do not want to use Java 7, you can get the same behavior with Apache IO.

From the official documentation:

FileAlterationObserver represents the state of files below a root directory, checking the filesystem and notifying listeners of create, change or delete events.

Here is how you can add listeners to define operations to be executed when such events happen.

  File directory = new File(new File("."), "src");
  FileAlterationObserver observer = new FileAlterationObserver(directory);
  observer.addListener(...);
  observer.addListener(...);

You will have to register the oberver(s) with a FileAlterationMonitor. Continuing from the same documentation:

  long interval = ...
  FileAlterationMonitor monitor = new FileAlterationMonitor(interval);
  monitor.addObserver(observer);
  monitor.start();
  ...
  monitor.stop();

Where interval is the amount of time (in miliseconds) to wait between checks of the file system.

Look for package named org.apache.commons.io.monitor in the library.