Java Review - 使用Event Bus实现目录变化的监控

简介: Java Review - 使用Event Bus实现目录变化的监控

195d03d17afc4a928bc581f313b01dfe.png


Pre

Java Review - Java进程内部的消息中间件_Event Bus设计模式


需求

监控文件的实时变化 , 就这一句话???


分析一下其中一个有问题的思路:


程序首次启动时获取该文件的最后修改时间并且做文件的首次解析,然后每隔一段指定的时间检查一次文件最后被修改的时间,如果与记录的时间相等则等待下次的采集(Balking Pattern),否则进行新一轮的采集并且更新时间。


这。。。。有问题啊 , 比如在采集时间间隔内,文件发生了N次变化,只能获取到最后一次,其根本原因是文件的变化不会通知到应用程序, 我只能傻傻的轮询~


新思路:


JDK自1.7版本后提供了WatchService类,该类可以基于事件通知的方式监控文件或者目录的任何变化,文件的改变相当于每一个事件(Event)的发生,针对不同的时间执行不同的动作,结合NIO2.0中提供的WatchService和Event Bus实现文件目录的监控的功能。


Event Bus案例实战

import com.artisan.bfzm.eventbus.EventBus;
import java.nio.file.*;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/12/2 16:37
 * @mark: show me the code , change the world
 */
public class DirectoryTargetMonitor {
    private WatchService watchService;
    private final EventBus eventBus;
    private final Path path;
    private volatile boolean start = false;
    public DirectoryTargetMonitor(final EventBus eventBus,
                                  final String targetPath) {
        this(eventBus, targetPath, "");
    }
    /**
     *
     * 构造Monitor的时候需要传入EventBus以及需要监控的目录
     * @param eventBus
     * @param targetPath
     * @param morePaths
     */
    public DirectoryTargetMonitor(final EventBus eventBus,
                                  final String targetPath, final String... morePaths) {
        this.eventBus = eventBus;
        this.path = Paths.get(targetPath, morePaths);
    }
    public void startMonitor() throws Exception {
        this.watchService = FileSystems.getDefault().newWatchService();
        //为路径注册感兴趣的事件
        this.path.register(watchService,
                StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_CREATE);
        System.out.printf("The directory [%s] is monitoring... \n", path);
        this.start = true;
        while (start) {
            WatchKey watchKey = null;
            try {
                //当有事件发生时会返回对应的WatchKey
                watchKey = watchService.take();
                watchKey.pollEvents().forEach(event ->
                {
                    WatchEvent.Kind<?> kind = event.kind();
                    Path path = (Path) event.context();
                    Path child = DirectoryTargetMonitor.this.path.resolve(path);
                    //提交FileChangeEvent到EventBus
                    eventBus.post(new FileChangeEvent(child, kind));
                });
            } catch (Exception e) {
                this.start = false;
            } finally {
                if (watchKey != null) {
                    watchKey.reset();
                }
            }
        }
    }
    public void stopMonitor() throws Exception {
        System.out.printf("The directory [%s] monitor will be stop...\n", path);
        Thread.currentThread().interrupt();
        this.start = false;
        this.watchService.close();
        System.out.printf("The directory [%s] monitor will be stop done.\n", path);
    }
}


在创建WatchService之后将文件的修改、删除、创建等注册给了WatchService,在指定目录下发生诸如此类的事件之后便会收到通知,我们将事件类型和发生变化的文件Path封装成FileChangeEvent提交给Event Bus.

import java.nio.file.Path;
import java.nio.file.WatchEvent;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/12/2 16:48
 * @mark: show me the code , change the world
 */
public class FileChangeEvent {
    private final Path path;
    private final WatchEvent.Kind<?> kind;
    public FileChangeEvent(Path path, WatchEvent.Kind<?> kind) {
        this.path = path;
        this.kind = kind;
    }
    public Path getPath() {
        return path;
    }
    public WatchEvent.Kind<?> getKind() {
        return kind;
    }
}


FileChangeEvent是对WatchEvent.Kind和Path的包装,一旦目录发生任何改变,都会提交FileChangeEvent事件。

目录监控的程序我们已经实现了,下面就来写一个接受文件目录变化的Subscriber,也就是当目录发生变化时用来接受事件的方法

import com.artisan.bfzm.eventbus.Subscribe;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/12/2 17:06
 * @mark: show me the code , change the world
 */
public class FileChangeListener {
    @Subscribe
    public void onChange(FileChangeEvent event) {
        System.out.printf("%s-%s-%s\n", Thread.currentThread().getName(),event.getPath(), event.getKind());
    }
}


onChange方法由@Subscribe标记,但没有指定topic,当有事件发送到了默认的topic上之后,该方法将被调用执行,接下来我们将FileChangeListener的实例注册给Event Bus并且启动Monitor程序

import com.artisan.bfzm.eventbus.AsyncEventBus;
import com.artisan.bfzm.eventbus.EventBus;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/12/2 17:15
 * @mark: show me the code , change the world
 */
public class FileDirTest {
    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
        final EventBus eventBus = new AsyncEventBus(executor);
        //注册
        eventBus.register(new FileChangeListener());
        DirectoryTargetMonitor monitor = new DirectoryTargetMonitor(eventBus, "C:\\Users\\artisan\\Desktop\\aaa");
        monitor.startMonitor();
    }
}

小结


EventBus有点类似于GOF设计模式中的监听者模式,但是EventBus提供的功能更加强大,使用起来也更加灵活,EventBus中的Subscriber不需要继承任何类或者实现任何接口,在使用EventBus时只需要持有Bus的引用即可。


在EventBus的设计中有三个非常重要的角色(Bus、Registry和Dispatcher),Bus主要提供给外部使用的操作方法,Registry注册表用来整理记录所有注册在EventBus上的Subscriber,Dispatcher主要负责对Subscriber消息进行推送(用反射的方式执行方法),但是考虑到程序的灵活性,Dispatcher方法中又提供了Executor的多态方式。

相关文章
|
2月前
|
存储 监控 Java
【深度挖掘Java性能调优】「底层技术原理体系」深入探索Java服务器性能监控Metrics框架的实现原理分析(Counter篇)
【深度挖掘Java性能调优】「底层技术原理体系」深入探索Java服务器性能监控Metrics框架的实现原理分析(Counter篇)
29 0
|
4月前
|
消息中间件 设计模式 Java
Java Review - Java进程内部的消息中间件_Event Bus设计模式
Java Review - Java进程内部的消息中间件_Event Bus设计模式
62 0
|
2月前
|
监控 算法 Java
【深度挖掘Java性能调优】「底层技术原理体系」深入探索Java服务器性能监控Metrics框架的实现原理分析(Gauge和Histogram篇)
【深度挖掘Java性能调优】「底层技术原理体系」深入探索Java服务器性能监控Metrics框架的实现原理分析(Gauge和Histogram篇)
32 0
|
4月前
|
缓存 算法 安全
Java Review - 并发编程_前置知识二
Java Review - 并发编程_前置知识二
30 0
Java Review - 并发编程_前置知识二
|
4月前
|
C++ Java 容器
【Java每日一练】总目录(2023.3.11~5.18)共69篇
【Java每日一练】总目录(2023.3.11~5.18)共69篇
166 0
【Java每日一练】总目录(2023.3.11~5.18)共69篇
|
4月前
|
算法 安全 Java
Java Review - 并发编程_ConcurrentLinkedQueue原理&源码剖析
Java Review - 并发编程_ConcurrentLinkedQueue原理&源码剖析
38 0
|
4月前
|
设计模式 安全 Java
Java Review - 并发编程_独占锁ReentrantLock原理&源码剖析
Java Review - 并发编程_独占锁ReentrantLock原理&源码剖析
39 0
|
14天前
|
JavaScript Java 测试技术
基于Java的新冠病毒校园监控平台的设计与实现(源码+lw+部署文档+讲解等)
基于Java的新冠病毒校园监控平台的设计与实现(源码+lw+部署文档+讲解等)
22 0
|
15天前
|
运维 监控 Java
Java 性能监控和故障排查技巧
【4月更文挑战第19天】Java应用的开发与运行需重视性能监控和故障排查,以确保稳定性和可靠性。利用日志记录、系统性能指标和VisualVM等工具进行监控。通过错误日志分析、分阶段测试、内存和线程分析来排查问题。关注性能瓶颈定位,并提前规划、定期监控,提升数据分析能力和团队协作,以优化应用性能。
|
26天前
|
监控 Java Linux
linux下监控java进程 实现自动重启服务
linux下监控java进程 实现自动重启服务