Java 监控本地某路径下是否有数据生成并进行相应处理

背景:本地某路径下中有数据生成,需要对其进行监控,并进行相应处理
CODE的分析:
启动文件服务,数据生成处理

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Path;

@Service
public class HandleService implements InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(HandleService.class);

    private UserConfiguration userConfiguration;

    @Override
    public void afterPropertiesSet() throws Exception {
        String path = argumentNotNullAndNotEmpty(userConfiguration.getMonitorPath(),
                "test.user.monitor-path");
        File file = new File(path);
        if (!file.exists() || !file.isDirectory()) {
            throw new FileNotFoundException("没有找到文件夹" + file.getAbsolutePath());
        }
        String extension = userConfiguration.getExtension();
        if (extension == null) {
            extension = "";
        } else {
            extension = extension.trim();
        }
        Path monitorPath = file.toPath();
        FileMonitor monitor = new FileMonitor(monitorPath, LOGGER, extension);
        monitor.start(this::handleEvent, true); //调用文件监控服务,并启动
    }

    private void handleEvent(String params) {
        //对新数据的生成进行相应的处理
        //TO DO Something
    }

    private String argumentNotNullAndNotEmpty(String value, String name) {
        if (value == null) {
            throw new NullPointerException(name);
        }
        value = value.trim();
        if (value.isEmpty()) {
            throw new IllegalArgumentException(name);
        }
        return value;
    }

    @Autowired
    public void setUserConfiguration(UserConfiguration userConfiguration) {
        this.userConfiguration = userConfiguration;
    }
}

启动文件服务,数据生成处理类

import org.slf4j.Logger;

import java.nio.file.*;
import java.util.function.Consumer;

public class FileMonitor {
    private final Path monitorPath;
    private final Logger logger;
    private final String extension;

    public FileMonitor(Path monitorPath, Logger logger, String extension) {
        this.monitorPath = monitorPath;
        this.logger = logger;
        this.extension = extension;
    }

    public void start(Consumer<String> consumer, boolean autoRestart) {
        new Thread(() -> {
            try {
                start(consumer);
            } catch (Exception e) {
                if (autoRestart) {
                    logger.info("尝试重启文件监视服务");
                    start(consumer, true);
                }
            }
        }, "FileMonitor").start();
    }

    private void start(Consumer<String> consumer) throws Exception {
        try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
            monitorPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
            logger.info("文件监视服务开始服务:监视文件夹{}", monitorPath.toString());
            WatchKey key;
            while ((key = watchService.take()) != null) {
                for (WatchEvent<?> event : key.pollEvents()) {
                    Path path = monitorPath.resolve((Path) event.context());
                    String filename = path.toString();
                    if (!Files.isDirectory(path) && filename.endsWith(extension) && !filename.endsWith(".temp")) {
                        logger.info("{}文件发生了{}事件!", getFileName(filename), event.kind());
                        consumer.accept(filename);
                    }
                }
                boolean valid = key.reset();
                if (!valid) {
                    throw new Exception("watchKey重置失败");
                }
            }
        } finally {
            logger.error("文件监视服务停止服务");
        }
    }

    private String getFileName(String fullPath) {
        int index = fullPath.lastIndexOf('\\');
        if (index > 0 && index < fullPath.length()) {
            return fullPath.substring(index + 1);
        }
        return fullPath;
    }
}

配置类

appilication.properties文件
#文件路径
test.user.monitor-path=D://data
test.user.extension=.zip

配置类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;


@Component
@Data
@ConfigurationProperties(prefix = "test.user")
public class UserConfiguration {
    private String monitorPath;
    private String extension;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值