3.2日学习打卡----初学FastDFS(二)

3.2日学习打卡

目录:

SpringBoot整合FastDFS

由GitHub大牛tobato在原作者YuQing与yuqih发布的JAVA客户端基础上进行了大量重构工作,并于GitHub上发布了FastDFS-Client1.26.5。

主要特性

  • 对关键部分代码加入了单元测试,便于理解与服务端的接口交易,提高接口质量
  • 将以前对byte硬解析风格重构为使用对象+注解的形式,尽量增强了代码的可读性
  • 支持对服务端的连接池管理
  • 支持上传图片时候检查图片格式,并且自动生成缩略图
  • 在SpringBoot当中自动导入依赖

实战开发

导入FastDFS依赖jar

xml 复制代码
<dependency>
  <groupId>com.github.tobato</groupId>
  <artifactId>fastdfs-client</artifactId>
  <version>1.26.5</version>
</dependency>

配置application.yml

yml 复制代码
# 分布式文件系统FDFS配置
fdfs:
  #连接时间
  so-timeout: 1501
  #超时时间
  connect-timeout: 601
  thumb-image:       #缩略图生成参数
    width: 150
    height: 150
  tracker-list:       #TrackerList参数,支持多个
    - 192.168.66.100:22122
    - 192.168.66.101:22122

上传文件操作

java 复制代码
package com.jjy.fastdfsemo;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;

@SpringBootTest
class FastDfSemoApplicationTests {

    @Autowired
     private FastFileStorageClient fastFileStorageClient;
    /**
     * 测试springboot环境下javaapi对分布式会问你系统上传文件的操作
     *
     */
    @Test
   public void testupload() throws FileNotFoundException {
       //获取本地文件
       File file = new File("C:\\Users\\SF\\Pictures\\联想锁屏壁纸\\2.jpg");
       //创建文件输入流
       FileInputStream fileInputStream = new FileInputStream(file);
       //文件上传
       /**
        *文件上传:参数一:传输文件内容的输入流;
        * 参数二:文件的size;
        * 参数三:文件扩展名;
        * 参数四:描述文件的元数据;返回值:上传文件在存储节点的唯一标识(卷名+文件名)
        */
       StorePath storePath = fastFileStorageClient.uploadFile(fileInputStream, file.length(), "jpg", null);
       //将卷名与文件名一起打印
       System.out.println(storePath.getFullPath());
       //将卷名与文件名分别打印
       System.out.println(storePath.getGroup()+" | "+storePath.getPath());


   }

}

配置SpringBoot的入口类

java 复制代码
package com.jjy.fastdfsemo;

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

//获取带有连接池的FastDFS Java客户端
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication
public class FastDfSemoApplication {

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

}

文件下载的操作

java 复制代码
package com.jjy.fastdfsemo;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;

@SpringBootTest
class FastDfSemoApplicationTests {

    @Autowired
     private FastFileStorageClient fastFileStorageClient;
    /**
     * 测试springboot环境下javaapi对分布式会问你系统上传文件的操作
     *
     */
  
    /**
     * 测试springboot环境下的javaAPI对分布式文件系统的下载文件的操作
     * @throws IOException
     */
    @Test
    public void testDownload() throws IOException {
        /**
         * 参数一:文件处于存储节点的卷名;
         * 参数二:文件在存储节点的文件名;
         * 参数三:下载的回调函数;返回值:文件内容的字节数组
         */
        byte[] bytes = fastFileStorageClient.downloadFile("group1", "M00/00/00/wKhCZGXi97mAK1ciAAJgIQIm2Ts043.jpg", new DownloadByteArray());
        //创建文件输出流,指定输出位置及文件名
        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\SF\\Pictures\\联想锁屏壁纸\\66.jpg");
        //使用文件输出流将文件内容字节数组写出
        fileOutputStream.write(bytes);
        //刷新输出流
        fileOutputStream.flush();
        //关闭输出流
        fileOutputStream.close();
    }


}

文件上传


引入Thymeleaf视图解析器

xml 复制代码
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

下载wangEditor富文本编辑器

wangEditor4 ------ 轻量级 web 富文本编辑器,配置方便,使用简单。

官网:www.wangeditor.com

文档:www.wangeditor.com/v4

使用CDN的形式引入

html 复制代码
<script
  type="text/javascript"
  src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"
></script>
<script type="text/javascript">
  const E = window.wangEditor
  const editor = new E("#div1")
  // 或者 const editor = new E(document.getElementById('div1'))
  editor.create()
</script>

编写index页面

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wangEditor demo</title>
</head>
<body>

<div id="div1">
    <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>


</body>

<script
        type="text/javascript"
        src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"
></script>
<!-- 引入 wangEditor.min.js -->
<script type="text/javascript">
    const E = window.wangEditor
    const editor = new E('#div1')
    // 或者 const editor = new E( document.getElementById('div1') )
    //设置文件上传的参数名称
    editor.config.uploadFileName = 'files'
    // 配置 server 接口地址
    editor.config.uploadImgServer = '/upload'
    // 2M
    editor.config.uploadImgMaxSize = 2 * 1024 * 1024
    editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
    // 一次最多上传 5 个图片
    editor.config.uploadImgMaxLength = 5
    editor.create()
</script>



</html>

编写Controller接口

java 复制代码
package com.jjy.fastdfsemo.controller;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class UploadController {
    //fastdfs存储节点的客户端对象
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    /**
     * 图片的上传
     * @param files
     */
    @PostMapping("/upload")
    public void upload(MultipartFile[] files){
        //判断是否上传图片
        if(files != null && files.length != 0 ){
            for (MultipartFile multipartFile : files){
                //获取上传文件名
                String filename = multipartFile.getOriginalFilename();
                //获取最后一个"."的下标,并获取从这个下标的下一个下标开始后的字符作为文件后缀
                String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1);
                StorePath storePath = null;
                try {
                    //上传文件
                    storePath = fastFileStorageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), fileSuffix, null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //打印返回的文件在存储节点的唯一标识
                System.out.println(storePath.getFullPath());
            }
            }
        }

}

FastDFS集成Nginx


FastDFS集成Nginx的2个原因

  • 为分布式文件系统提供Http服务支持

    通过Nginx的web服务代理访问分布式文件系统的存储节点,从而实现通过http请求访问存储节点资源。

注意:

src 属性值图像文件的 URL。也就是引用该图像的文件的的绝对路径或相对路径。

  • 解决复制延迟问题

    由于FastDFS的同卷的存储节点之间需要同步,当文件尚未同步完成时,访问请求到达改节点,获取的数据将是未同步完的不完整数据,即为复制延迟问题。通过Nginx检测请求的存储节点的数据,若该存储节点的数据尚未同步完成,则将请求转发至数据的原存储节点,从而解决复制延迟问题。

环境搭建

下载Fastdfs的Nginx模块包

复制代码
cd /usr/local
wget https://github.com/happyfish100/fastdfs-nginx-module/archive/V1.22.tar.gz
tar -zxvf V1.22.tar.gz

安装Nginx依赖文件

复制代码
yum install -y gcc gcc-c++ zlib zlib-devel openssl openssl-devel pcre pcre-devel gd-devel epel-release

下载Nginx软件包

复制代码
wget https://nginx.org/download/nginx-1.19.2.tar.gz
cd nginx-1.19.2/

配置Nginx服务器

复制代码
#建立Makefile文件,检查Linux系统环境以及相关的关键属性。
./configure --add-module=/usr/local/fastdfs-nginx-module-1.22/src/
#编译项目,主要将gcc源代码编译成可执行的目标文件
make
#根据上一步骤编译完成的数据安装到预定的目录中。
make install

注意:

--add-module:为nginx添加一个fastdfs-nginx-module模块,值为该模块在当前系统的路径

--prefix:指定nginx安装位置

将Fastdfs软件包里面的http.conf和mime.types拷贝到/etc/fdfs目录下

复制代码
cp /usr/local/src/fastdfs-6.06/conf/mime.types /etc/fdfs/
cp /usr/local/src/fastdfs-6.06/conf/http.conf /etc/fdfs/

配置Nginx的fastdfs模块,并编辑文件

复制代码
#拷贝文件
[root@localhost opt]cp /usr/local/fastdfs-nginx-module-1.22/src/mod_fastdfs.conf /etc/fdfs/
[root@localhost fdfs] vim mod_fastdfs.conf
#保存日志目录
base_path=/data/fastdfs/storage   
#tracker 服务器的 IP 地址以及端口号
tracker_server=192.168.66.100:22122 
#文件url中是否有group 名
url_have_group_name = true      
#存储路径
store_path0=/data/fastdfs/storage  
group_count = 1            #设置组的个数
#然后在末尾添加分组信息,目前只有一个分组,就只写一个
[group1]
group_name=group1
storage_server_port=23000
store_path_count=1
store_path0=/data/fastdfs/storage

配置Nginx

复制代码
server {
  listen    80;
  server_name  localhost;
   
  location ~ /group[1-3]/M00 {
    alias /data/fastdfs/storage/data;
     ngx_fastdfs_module;
   }
  # 根目录下返回403
  location = / {
     return 403;
   }
  # log file
  access_log  logs/img_access.log access;
}

启动Ningx服务

复制代码
# 进入sbin目录
[root@tracker nginx]# cd sbin/
# 启动服务 -c:指定配置文件
[root@tracker sbin]# ./nginx -c /usr/local/nginx/conf/nginx.conf

查看服务启动情况

复制代码
[root@tracker sbin]# ps -ef | grep nginx

启动追踪服务与存储节点服务

复制代码
[root@tracker sbin]# fdfs_trackerd /etc/fdfs/tracker.conf start
[root@tracker sbin]# fdfs_storaged /etc/fdfs/storage.conf start

上传图片测试

将图片上传至linux系统后,使用指令上传至分布式文件系统

复制代码
[root@tracker fdfs]# fdfs_upload_file /etc/fdfs/client.conf /root/xxxxx.png
group1/M00/00/00/wKhyj1wrIUWAL5ASAAAfA8PiO7Y493.png

通过浏览器远程访问

复制代码
http://192.168.66.100/group1/M00/00/00/wKhyj1wrIfqAD3NFAAn1fNRE8_M976.png

如果我的内容对你有帮助,请点赞,评论,收藏。创作不易,大家的支持就是我坚持下去的动力

相关推荐
西岸行者9 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
悠哉悠哉愿意9 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
别催小唐敲代码9 天前
嵌入式学习路线
学习
毛小茛9 天前
计算机系统概论——校验码
学习
babe小鑫9 天前
大专经济信息管理专业学习数据分析的必要性
学习·数据挖掘·数据分析
winfreedoms9 天前
ROS2知识大白话
笔记·学习·ros2
在这habit之下9 天前
Linux Virtual Server(LVS)学习总结
linux·学习·lvs
我想我不够好。9 天前
2026.2.25监控学习
学习
im_AMBER9 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
CodeJourney_J9 天前
从“Hello World“ 开始 C++
c语言·c++·学习