越寫悅快樂之Spring Boot項目如何連接Samba服務

今天的越寫悅快樂之系列文章爲大家帶來Spring Boot項目如何連接Samba服務。作爲一名愛做夢的碼農來說,探索未知的領域並應用是我們不懈的追求,當然這些應用也需要建立在特定的場景下才能發揮潛能,也更能通過產品或服務滿足客戶的需求,接下來我們通過Samba來構建我們的文件服務,通過它可以快速讀寫文件,接下來讓我們來看看。

Samba是一個應用於Linux和Unix的Windows應用程序套件,它爲所有使用SMB/CIFS協議的客戶機提供了安全、穩定和快速的文件和打印服務。

開發環境

  • Window 10.0.17763
  • IntelliJ IDEA 2019.1
  • Spring Boot 2.3.7

創建Samba服務

爲了能快速創建Samba服務,我們在Linux主機上使用Docker來進行相關操作

Linux下Docker的安裝請自行搜索

拉取鏡像

我們通過SSH連接Linux服務器,然後在終端軟件Xshell中執行以下命令:

docker pull dperson/samba

創建映射目錄

mkdir -p /home/docker/samba/data

啓動鏡像

在啓動容器的時候需要指定工作目錄、連接Samba的賬號和密碼、映射目錄的讀寫規則,具體的啓動命令如下:

docker run -it --name samba -p 139:139 -p 445:445 -v /home/docker/samba/data:/home/shares/shareA -d dperson/samba -w "WORKGROUP" -u "smbuser;123456789" -s "shareA;/home/shares/shareA;yes;no;no;smbuser;smbuser;smbuser"

可以通過docker ps -a查看Samba容器服務是否啓動

接入步驟

創建項目

我們使用IntelliJ IDEA創建項目samba-tour,然後引入jcifs依賴,Maven的配置文件參考以下內容:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>me.weitao.app</groupId>
    <artifactId>samba-tour</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>samba-tour</name>
    <description>Samba Tour for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <jcifs.version>2.1.22</jcifs.version>
    </properties>

    <repositories>
        <repository>
            <id>AliYun Nexus</id>
            <name>AliYun Nexus</name>
            <url>https://maven.aliyun.com/nexus/content/repositories/central</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>AliYun Nexus</id>
            <name>AliYun Nexus</name>
            <url>https://maven.aliyun.com/nexus/content/repositories/central</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.codelibs/jcifs -->
        <dependency>
            <groupId>org.codelibs</groupId>
            <artifactId>jcifs</artifactId>
            <version>${jcifs.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

編寫測試文件

隨後我們查看一下項目的結果,如下圖所示:

SambaTourApplicationTests文件中編寫讀寫文件的函數,可參考一下內容:

package me.weitao.app;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;

@SpringBootTest
@Slf4j
class SambaTourApplicationTests {

    public static void smbGet(String remoteUrl, String localDir) {
        System.out.println("進入 smbGet() ....");
        InputStream in = null;
        OutputStream out = null;

        try {
            SmbFile remoteFile = new SmbFile(remoteUrl);
            System.out.println(remoteFile.exists());
            System.out.println(remoteFile.canRead());
            System.out.println(remoteFile.canWrite());
            System.out.println("嘗試連接 遠程文件 ....");
            if (remoteFile.exists()) {
                log.info("找到文件....");
                String fileName = remoteFile.getName();
                File localFile = new File(localDir + "\\" + fileName);
                in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
                out = new BufferedOutputStream(new FileOutputStream(localFile));
                byte[] buffer = new byte[1024];
                while (in.read(buffer) != -1) {
                    out.write(buffer);
                    buffer = new byte[1024];
                }
            } else {
                log.info(remoteUrl + "文件不存在!");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void smbPut(String remoteUrl, String localFilePath) {

        InputStream in = null;
        OutputStream out = null;

        try {

            File localFile = new File(localFilePath);
            String fileName = localFile.getName();
            SmbFile remoteFile = new SmbFile(remoteUrl + "/" + fileName);
            in = new BufferedInputStream(new FileInputStream(localFile));
            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                out.close();
                out = null;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    void contextLoads() {

                    //    smbGet("smb://smbuser:[email protected]/shareA/def.txt", "F:/shareA");

        // smbPut("smb://smbuser:[email protected]/shareA", "F:\\shareA\\def.txt");

    }

}

shareA是我們Docker啓動時的映射路徑
smbuser:123456789是我們連接Samba的賬號和密碼
192.168.8.192是我們的Linux主機的IP地址

創建測試文件

在執行測試函數之前,我們需要在shareA目錄下創建文件def.txt,並寫入以下內容:

welcome to samba

查看結果

隨後我們執行測試函數,調用smbPut方法並傳入需要連接的Samba信息,以及本地文件路徑,執行結果如下圖所示:

驗證結果

隨後我們按下Windows + R並輸入\\192.168.8.192,如果出現你不能訪問此共享文件夾,因爲你組織的安全策略阻止未經身份驗證的來賓訪問的警告,請參考這篇文章來解決,隨後我們再次輸入\\192.168.8.192提示我們輸入身份驗證信息,輸入我們在Samba容器啓動時配置的賬號和密碼,在shareA目錄中可以看到剛纔執行測試的文件了。

參考

個人收穫及總結

文件系統作爲一個產品的常用服務,可以快速搭建基礎服務,當然這些基礎設施需要我們根據實際業務去梳理和調整,通過不斷地優化和打磨才能讓我們的產品和服務更上一層樓,也希望我們能爲互聯網的發展貢獻自己的一份力量,讓我們一起構建自己的核心競爭力。若是我的文章對你有所啓發,那將是我莫大的榮幸。希望和您一起精進,成爲更好的自己。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章