SpringBoot中实现文件监听

SpringBoot中实现文件监听并在数据库中保存对该文件的操作记录

实现方式:org.apache.commons.io.monitor.FileAlterationObserver

1.创建一个项目启动时就启动的方法,来开启监听(实现ApplicationRunner接口,重写run方法)

/**
 * 项目启动时执行的方法
 * @author daiguojun
 */
@Component
@Slf4j
public class MyApplicationRunner implements ApplicationRunner {
   
   //读取配置文件中了文件路径 拿到要监听的文件夹
    @Value("${file.path}")
    private String path;

    @Override
    public void run(ApplicationArguments args) {
        try {
            // 构造观察类主要提供要观察的文件或目录,当然还有详细信息的filter
            FileAlterationObserver observer = new FileAlterationObserver(new File(path));
            // 构造收听类
            FileListener listener = new FileListener();
            // 为观察对象添加收听对象
            observer.addListener(listener);
            // 配置Monitor,第一个参数单位是毫秒,是监听间隔;第二个参数就是绑定我们之前的观察对象。
            FileAlterationMonitor fileMonitor = new FileAlterationMonitor(10000, new FileAlterationObserver[] { observer });
            // 启动监听
            fileMonitor.start();
        } catch (Exception e) {
            log.info("启动失败!");
            e.printStackTrace();
        }
    }
}

2.新建类,重写FileAlterationListener接口

/**
 * @Author: daiguojun
 * @CreateDate: 2021/3/31 16:52
 * @Description: 监听文件的创建删除修改  (并在数据库中保存相关的记录)
 */
@Slf4j
@Component
public class FileListener implements FileAlterationListener {

    private Dao dao;

    @Override
    public void onStart(FileAlterationObserver fileAlterationObserver) {
        orderDao = SpringUtil.getBean(dao.class);
    }

    @Override
    public void onDirectoryCreate(File file) {
        log.info(file.getPath()+"---该路径下新建了一个文件夹");
    }

    @Override
    public void onDirectoryChange(File file) {
        log.info(file.getPath()+"--文件夹发生改变");
    }

    @Override
    public void onDirectoryDelete(File file) {
        log.info(file.getPath()+"---文件夹被删除");
    }

    @Override
    public void onFileCreate(File file) {
        //把被创建的文件信息存放到数据库
        log.info("文件被创建:"+file.getPath());
        //数据入库
        try {
            Object o = dao.selectFileInfo(file.getPath());
            if(o == null){
                long l = file.lastModified();
                String id = UUID.randomUUID().toString().replace("-","");
                Date date = new Date(l);
                String filePath = file.getPath();
                String fileName = file.getName();
                long length = file.length();
                String fileSize = String.valueOf(length);
                orderDao.insertFileInfo(id,date,date,filePath,fileName,fileSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFileChange(File file) {
        log.info("文件发生改变"+file.getPath());
        //记录文件在什么时间发生改变
        try {
            String name = file.getPath();
            long l = file.lastModified();
            Date date = new Date(l);
            String time = DateUtil.formatDateTime(date, "yyyy-MM-dd HH:mm:ss");
            orderDao.updateOrderFileInfo(time,name);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onFileDelete(File file) {
        log.info("文件被删除"+file.getPath());
        //记录文件什么时间被删除同时清除数据库中存在的记录
        try {
            Object o = dao.selectInfo(file.getPath());
            if(o != null){
                dao.deleteByFileName(file.getPath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStop(FileAlterationObserver fileAlterationObserver) {
        //监听结束时执行的方法
    }
}

注意: 因为实现了FileAlterationListener接口,所以通过Autowried的方式注入dao层会注入失败。

解决办法:可以从Spring容器中直接或去bean对象,上文通过springUtil的getBean方法实现。

监听某一文件夹可能会加重这个文件夹的压力,尤其是如果这个文件夹在共享盘,可能会影响共享盘的读取速率

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot使用AOP监听注解可以通过以下步骤实现: 1. 在`pom.xml`文件添加`spring-boot-starter-aop`依赖,以使用Spring AOP。 2. 创建一个注解类,例如`@MyAnnotation`,用于标记需要被监听的方法。 3. 创建一个切面类,用于监听被`@MyAnnotation`标记的方法。可以使用`@Aspect`注解来标记这个类。 4. 在切面类定义一个切点,用于匹配被`@MyAnnotation`标记的方法。可以使用`@Pointcut`注解来定义切点。 5. 在切面类定义一个通知,用于在匹配到切点时执行某些操作。可以使用`@Before`、`@After`、`@Around`等注解来定义通知。 6. 在Spring Boot应用程序的主类添加`@EnableAspectJAutoProxy`注解,以启用AOP功能。 以下是一个示例代码: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { } @Aspect @Component public class MyAspect { @Pointcut("@annotation(com.example.demo.MyAnnotation)") public void myAnnotationPointcut() {} @Before("myAnnotationPointcut()") public void beforeMyAnnotation() { System.out.println("Before My Annotation"); } } @EnableAspectJAutoProxy @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 在上面的示例,`@MyAnnotation`注解用于标记需要被监听的方法,在`MyAspect`切面类定义了一个切点`myAnnotationPointcut`,用于匹配被`@MyAnnotation`标记的方法,在`beforeMyAnnotation`方法定义了一个前置通知,在匹配到切点时执行。在`DemoApplication`主类添加了`@EnableAspectJAutoProxy`注解,以启用AOP功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

对你偏爱u

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值