分布式文件服务器FastDFS----总结

2022-07-24,,

分布式文件服务器FastDFS

什么是FastDFS

  • 描述:是一个分布式文件上传工具(文件数据库 SQL)
  • 作用:将文件上传到服务器

怎么用

理论概念
运行流程
1)存储服务器定时上传状态到调度服务器
2)客户端访问调度器获取可以使用的存储服务器地址
3)客户端将文件上传至指定存储服务器
4)存储生成fileID,并将文件存入磁盘
5)返回fileId给客户端

fileID的结构
组名/磁盘路径/两级数据路径/文件名

编写步骤
a、导包fastdfs-client

 <!--文件服务器客户端-->
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.26.1-RELEASE</version>
        </dependency>

b、编写核心配置文件,详见application.yml

server:
  port: 8081

fdfs:
  connect-timeout: 600
  so-timeout: 15000
  tracker-list: 192.168.25.133:22122
  thumb-image:
    height: 150
    width: 150
  pool:
    max-total: 50
  #自定义属性
  fastLocalhost: http://192.168.25.133/
  fastHost: 80
spring:
  freemarker:
    template-loader-path: /templaters/
    suffix: .ftl

c、导入配置类
CommonFileUtil.java

import com.github.tobato.fastdfs.domain.MateData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Set;
// 操作文件的工具类
@Component
public class CommonFileUtil {

    private final Logger logger = LoggerFactory.getLogger(CommonFileUtil.class);

    @Autowired
    private FastFileStorageClient storageClient;


    /**
     *	MultipartFile类型的文件上传ַ
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }

    /**
     * 普通的文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        StorePath path = storageClient.uploadFile(inputStream, file.length(),
                FilenameUtils.getExtension(file.getName()), null);
        return getResAccessUrl(path);
    }

    /**
     * 带输入流形式的文件上传
     *
     * @param is
     * @param size
     * @param fileName
     * @return
     */
    public String uploadFileStream(InputStream is, long size, String fileName) {
        StorePath path = storageClient.uploadFile(is, size, fileName, null);
        return getResAccessUrl(path);
    }

    /**
     * 将一段文本文件写到fastdfs的服务器上
     *
     * @param content
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
            byte[] buff = content.getBytes(Charset.forName("UTF-8"));
            ByteArrayInputStream stream = new ByteArrayInputStream(buff);
            StorePath path = storageClient.uploadFile(stream, buff.length, fileExtension, null);
            return getResAccessUrl(path);
    }

    /**
     * 返回文件上传成功后的地址名称ַ
     * @param storePath
     * @return
     */
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 删除文件
     * @param fileUrl
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            logger.warn(e.getMessage());
        }
    }

    public String upfileImage(InputStream is, long size, String fileExtName, Set<MateData> metaData) {
        StorePath path = storageClient.uploadImageAndCrtThumbImage(is, size, fileExtName, metaData);
        return getResAccessUrl(path);
    }


}

fdfsConfig.java


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class FdfsConfig {

    @Value("${fdfs.fastLocalhost}")
    private String resHost;

    @Value("${fdfs.fastHost}")
    private String storagePort;

    public String getResHost() {
        return resHost;
    }

    public void setResHost(String resHost) {
        this.resHost = resHost;
    }

    public String getStoragePort() {
        return storagePort;
    }

    public void setStoragePort(String storagePort) {
        this.storagePort = storagePort;
    }

}

FdfsConfiguration.java

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;

@Configuration
@EnableMBeanExport(registration= RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfiguration {
}

d、修改启动类
@Import(FdfsClientConfig.class)



import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

import java.rmi.registry.Registry;

@SpringBootApplication
@Import(FdfsClientConfig.class)
public class FastDFSApplication {

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

    }
}

e、编写文件上传代码
前端:
文件上传两要素:
提交方式:POST
配置enctype属性:enctype=multiparty/form-data

后台:
依赖注入(commonFileUtil,FdfsConfig)
编写处理请求的方法:
入参:MultiPartFile类型的参数,参数名=控件name属性
处理逻辑:
1)判断参数是否为空
2)上传文件,获取fileID
3)拼接url = FdfsConfig.redHost+fileID
4)返回界面,并显示


@Controller
public class FileUploadController {

    @Autowired
    private CommonFileUtil commonFileUtil;
    @Autowired
    private FdfsConfig config;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(MultipartFile files,Model model){
        //判断文件是否为空
        String url = null;
        if(!files.isEmpty()){

            try {
                //进行文件上传,获取fileId
                String fileId = commonFileUtil.uploadFile(files);
                //拼接图片访问路径
                url = config.getResHost()+fileId;
                model.addAttribute("url", url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "success";
    }

文件上传需要安装虚拟机,上传到服务器,以下是教程
1.安装VMware-workstation-full-14.1.2-8497320
安装完成后激活,激活好后打开,主页是这样的:

2.还需要pinyougou-image-server文件夹

3.在VMware Workstation中导入虚拟机
点击文件>打开,

导入此虚拟机

这里要修改以下设置,最好关闭防火墙

运行虚拟机,用户名root,密码itcast
注意密码是不能显示的,只能盲打

登录成功,在cmd窗口能正确显示这些,基本就能完成文件上传了。

启动虚拟机时遇到的问题

解决办法:
重新启动计算机,进入BIOS模式,按方向键选择“Configuration”,按下方向键选择Intel Virtual Technology选项,该选项为Intel虚拟化技术选项。
按下回车键选择Enabled,按下F10保存设置即可。

本文地址:https://blog.csdn.net/qq_45928896/article/details/114193358

《分布式文件服务器FastDFS----总结.doc》

下载本文的Word格式文档,以方便收藏与打印。