要创建一个Spring Boot项目并编写pom.xml文件,你可以按照以下步骤操作:

1. 使用Maven创建Spring Boot项目

使用Maven命令创建一个新的Spring Boot项目:

mvn archetype:generate -DgroupId=com.example -DartifactId=demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

2. 配置 pom.xml 文件

进入项目目录后,编辑pom.xml文件以包含Spring Boot依赖和插件:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- Spring Boot Web Starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- JSch for SSH connection -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>

        <!-- Spring Boot Test Starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Spring Boot Maven Plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3. 创建Spring Boot主应用程序类

src/main/java/com/example/demo目录下创建一个主应用程序类:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

4. 创建控制器和服务类

创建控制器类和服务类用于监听任务和处理业务逻辑:

package com.example.demo;

import com.jcraft.jsch.*;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.security.MessageDigest;
import java.security.DigestInputStream;
import java.util.Properties;

@RestController
@RequestMapping("/monitor")
public class RemoteFileMonitorController {
    private final RemoteFileMonitorService monitorService = new RemoteFileMonitorService();

    @PostMapping("/start")
    public String startMonitor(@RequestParam long timeout) {
        monitorService.startMonitoring(timeout);
        return "Monitoring started.";
    }

    @PostMapping("/stop")
    public String stopMonitor() {
        monitorService.stopMonitoring();
        return "Monitoring stopped.";
    }
}

class RemoteFileMonitorService {
    private static final String REMOTE_HOST = "your-remote-host";
    private static final int REMOTE_PORT = 22; // 默认SSH端口
    private static final String USERNAME = "your-username";
    private static final String PASSWORD = "your-password";
    private static final String REMOTE_DIR = "/path/to/remote/directory";
    private static final String LOCAL_DIR = "/path/to/local/data/";

    private Session session;
    private ChannelSftp sftpChannel;
    private boolean isRunning = false;
    private long timeout;

    public void startMonitoring(long timeout) {
        this.timeout = timeout;
        isRunning = true;
        new Thread(this::monitorDirectory).start();
    }

    public void stopMonitoring() {
        isRunning = false;
        disconnect();
    }

    private void connect() throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
        session.setPassword(PASSWORD);

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();
    }

    private void disconnect() {
        if (sftpChannel != null && sftpChannel.isConnected()) {
            sftpChannel.disconnect();
        }
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }

    private void monitorDirectory() {
        long startTime = System.currentTimeMillis();
        try {
            connect();
            while (isRunning && (System.currentTimeMillis() - startTime) < timeout) {
                for (Object obj : sftpChannel.ls(REMOTE_DIR)) {
                    if (obj instanceof ChannelSftp.LsEntry) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) obj;
                        String filename = entry.getFilename();
                        if (!filename.equals(".") && !filename.equals("..")) {
                            String localFilePath = LOCAL_DIR + filename;
                            downloadFile(filename, localFilePath);
                            System.out.println("Downloaded: " + filename);
                            stopMonitoring(); // Stop monitoring after processing the file
                            return;
                        }
                    }
                }
                Thread.sleep(5000); // 每隔一定时间检查一次,例如5秒
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            disconnect();
        }
    }

    private void downloadFile(String filename, String localFilePath) throws Exception {
        try (FileOutputStream fos = new FileOutputStream(localFilePath);
             InputStream inputStream = sftpChannel.get(REMOTE_DIR + "/" + filename)) {
            byte[] buffer = new byte[1024];
            int readCount;
            while ((readCount = inputStream.read(buffer)) > 0) {
                fos.write(buffer, 0, readCount);
            }
            System.out.println("MD5: " + calculateMD5(localFilePath));
        }
    }

    private String calculateMD5(String filePath) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (InputStream is = new FileInputStream(filePath);
             DigestInputStream dis = new DigestInputStream(is, md)) {
            while (dis.read() != -1) ; // empty loop to clear the data
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        }
    }
}

5. 运行项目

使用以下命令运行Spring Boot项目:

shmvn spring-boot:run 

或者编译和打包项目:

shmvn clean package 

然后运行生成的JAR文件:

shjava -jar target/demo-1.0-SNAPSHOT.jar 

6. 控制接口

你可以通过以下命令控制监听任务:

  • 启动监听任务,并设置最大等待时间为1小时(3600000毫秒):
shcurl -X POST "http://localhost:8080/monitor/start?timeout=3600000" 
  • 停止监听任务:
shcurl -X POST http://localhost:8080/monitor/stop 

这样,你就可以使用Java编写一个定时任务服务来监听远程虚拟机目录下的文件,并根据条件执行相应的操作。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐