Tienda e-commerce project_FastDFS almacenamiento distribuido de archivos (2)

1. Introducción a FastDFS

FastDFS es un software de código abierto y liviano, administra archivos, sus funciones incluyen almacenamiento de archivos, sincronización de archivos, acceso a archivos (carga de archivos, descarga de archivos), etc., lo que resuelve el problema del almacenamiento masivo y el equilibrio de carga. Especialmente adecuado para servicios en línea que utilizan archivos como portador, como sitios web de álbumes de fotos, sitios web de videos, etc.

FastDFS está hecho a medida para Internet, teniendo en cuenta todos los mecanismos como la copia de seguridad redundante, el equilibrio de carga y la expansión lineal, y prestando atención a indicadores como alta disponibilidad y alto rendimiento. Es fácil crear un clúster de servidor de archivos de alto rendimiento con FastDFS para proporcionar carga y descarga de archivos Y otros servicios.

La arquitectura FastDFS incluye el servidor Tracker y el servidor de almacenamiento. El cliente solicita al servidor Tracker que cargue y descargue archivos, y el servidor de almacenamiento completa la carga y descarga de archivos a través de la programación del servidor Tracker.

El servidor de seguimiento se utiliza para el equilibrio de carga y la programación. El servidor de seguimiento puede encontrar el servidor de almacenamiento para proporcionar servicios de carga de archivos de acuerdo con algunas estrategias al cargar archivos. El rastreador puede denominarse servidor de seguimiento o servidor de despacho. La función del servidor de almacenamiento es el almacenamiento de archivos. Los archivos cargados por el cliente finalmente se almacenan en el servidor de almacenamiento. El servidor de almacenamiento no implementa su propio sistema de archivos, pero utiliza el sistema de archivos del sistema operativo para administrar los archivos. El almacenamiento se puede llamar servidor de almacenamiento.

Dos, el código

Cree el submódulo changgou-service-file bajo el módulo changgou-service.

Archivo 1.pom

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>mychanggou-service</artifactId>
        <groupId>com.mychanggou</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>mycahnggou-service-file</artifactId>

    <dependencies>
        <!--  FastDFS  -->
        <dependency>
            <groupId>net.oschina.zcx7878</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.mychanggou</groupId>
            <artifactId>mychanggou-common</artifactId>
            <version>1.0-SNAPSHOT</version>
    </dependency>
    </dependencies>

</project>

2. La clase de inicio principal

package com.mychanggou;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * @author :LiuShihao
 * @date :Created in 2020/9/17 8:20 下午
 * @desc :
 * 启动报错  : 没有数据库信息配置, 因为不需要用到数据库,所以排除数据库自动加载
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableEurekaClient
public class FileApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(FileApplication.class);
    }
}

3.Información del archivo de configuración FastDFS

Crear nuevo en la carpeta de recursosfdfs_client.conf

connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.tracker_http_port = 80
tracker_server = 116.62.13.104:22122

4. Paquete de información de archivos

Las cargas de archivos generalmente tienen nombre de archivo, contenido de archivo, extensión de archivo, valor de archivo md5, autor del archivo y otros atributos relacionados.Podemos crear un objeto para encapsular estos atributos.

package com.mychanggou.file;

import lombok.Data;

/**
 * @author :LiuShihao
 * @date :Created in 2020/9/17 8:24 下午
 * @desc :
 * 封装文件上传信息
 *      时间:
 *      Author:
 *      type:
 *      size:
 *      附加信息:
 */
@Data
public class FastDFSFile {
    
    
    //文件名字
    private String name;
    //文件内容
    private byte[] content;
    //文件扩展名
    private String ext;
    //文件MD5摘要值
    private String  md5;
    //文件创建作者
    private String author;

    public FastDFSFile(String name, byte[] content, String ext, String height,String width, String author) {
    
    
        super();
        this.name = name;
        this.content = content;
        this.ext = ext;
        this.author = author;
    }
    public FastDFSFile(String name, byte[] content, String ext) {
    
    
        super();
        this.name = name;
        this.content = content;
        this.ext = ext;
    }

}

5. Empaquetar herramientas FastDFS

package com.mychanggou.util;

import com.mychanggou.file.FastDFSFile;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author :LiuShihao
 * @date :Created in 2020/9/17 8:29 下午
 * @desc :实现文件管理
 *          文件上传
 *          文件下载
 *          文件删除
 *          文件信息获取
 *          Storage信息获取
 *          Tracker信息获取
 *
 *
 */
public class FastDFSUtil {
    
    
    //加载Tracker连接信息
    static {
    
    
        try {
    
    
            //String fdfsconfpath = "/Users/LiuShihao/IdeaProjects/mychanggou/mychanggou-service/mycahnggou-service-file/src/main/resources/fdfs_client.conf";
            //查找classpath下的文件的路径
            String path = new ClassPathResource("fdfs_client.conf").getPath();
            ClientGlobal.init(path);
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     * @param fastDFSFile   上传的文件信息封装
     */
    public static String[] upload(FastDFSFile fastDFSFile) throws Exception {
    
    

        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);

        /**
         * 通过StorageClient访问Storage,实现文件上传,并获取文件上传后的存储信息
         * 1.上传文件的字节数组
         * 2. 上传文件的扩展名
         * 3. 上传文件的附加信息
         */
        //附加信息:  创建文件附加信息   可以用于文件上传的第三个参数   比如  Author:lsh   拍摄地址:上海   拍摄终端:iPhone 11 Pro Max
//        NameValuePair[] meta_list = new NameValuePair[1];
//        meta_list[0] = new NameValuePair("name",fastDFSFile.getAuthor());
        String[] upload = storageClient.upload_file(fastDFSFile.getContent(), fastDFSFile.getExt(), null);
        /**
         * upload_file返回参数:upload[]
         * 1. upload[0]:文件上传所存储的组名                  group1
         * 2. upload[1]:文件存储到Storage上的文件名字          M00/02/14/wyt.jpg
         * 也可以获得StorageClient1客户端 直接使用upload_file1 方法
         */
        return upload;
    }

    /**
     * 获取文件信息
     * @param groupName          group1
     * @param remoteFileName  M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg
     * @return
     * @throws Exception
     */
    public static FileInfo getFileInfo(String groupName, String remoteFileName) throws Exception {
    
    
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);

        return storageClient.get_file_info(groupName,remoteFileName);

    }

    /**
     * 下载文件
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws Exception
     */
    public static InputStream downloadFile(String groupName, String remoteFileName)throws Exception{
    
    
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);

        //文件下载
        byte[] bytes = storageClient.download_file(groupName, remoteFileName);

        return new ByteArrayInputStream(bytes);

    }

    /**
     * 删除文件
     * @param groupName
     * @param remoteFileName
     * @throws Exception
     */
    public static void deleteFile(String groupName, String remoteFileName)throws Exception{
    
    
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);

        //文件删除
        storageClient.delete_file(groupName,remoteFileName);

    }

    public static String getTrackerInfo()throws Exception{
    
    
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);
        //获取Tracker的端口
        String hostString = trackerServer.getInetSocketAddress().getHostString();
        int tracker_http_port = ClientGlobal.getG_tracker_http_port();
        String url = "http://"+hostString+":"+tracker_http_port;
        return  url;

    }

    /**
     * 获取TeackerServer
     * @return
     * @throws IOException
     */
    public static TrackerServer getTrackerServer() throws IOException {
    
    
        //创建一个Tracker访问的客户端对象TrackerClient
        TrackerClient trackerClient = new TrackerClient();

        //通过TrackerClient访问TrackerServer服务,获取连接信息
        TrackerServer trackerServer = trackerClient.getConnection();

        return trackerServer;

    }

    /**
     * 获取StorageClient
     * @param trackerServer
     * @return
     */
    public static StorageClient getStorageClient(TrackerServer trackerServer){
    
    
        //通过TrackerServer的连接信息可以获取Storage的连接信息,创建StorageClient对象存储storage连接信息
        StorageClient storageClient = new StorageClient(trackerServer, null);

        return storageClient;
    }








    public static void main(String[] args) throws Exception {
    
    
        //获取文件信息
//        FileInfo file = getFileInfo("group1", "M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg");
//        System.out.println("FileSize:"+file.getFileSize());
//        System.out.println("IPAddr:"+file.getSourceIpAddr());


//        //文件下载
//        InputStream is = downloadFile("group1", "M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg");
//        FileOutputStream os = new FileOutputStream("/Users/LiuShihao/Desktop/1.jpeg");
//        //定义一个缓冲区
//        byte[] buffer = new byte[1024];
//        while(is.read(buffer)!=-1){
    
    
//            os.write(buffer);
//        }
//        os.flush();
//        os.close();
//        is.close();

        //文件删除
//        deleteFile("group1", "M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg");
//      获取Tracker信息  IP+Port
//        System.out.println(getTrackerInfo());

    }
}

6. Capa de control

package com.mychanggou.controller;

import com.mychanggou.file.FastDFSFile;
import com.mychanggou.util.FastDFSUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author :LiuShihao
 * @date :Created in 2020/9/17 8:51 下午
 * @desc :
 */
@RestController
@RequestMapping("/file")
@CrossOrigin//跨域
public class FileUploadController {
    
    

    @PostMapping("/upload")
     public Result upload(@RequestParam("file")MultipartFile file) throws Exception {
    
    
        if(file == null){
    
    
            throw new RuntimeException("文件不存在");
        }
        //调用工具类  上传FastDFS文件服务器
        //使用StringUtils.getFilenameExtension 可以获取文件扩展名
        //获取文件名字、文件字节数组、文件扩展名   构造FastDFSFile对象

        FastDFSFile fastDFSFile = new FastDFSFile(file.getOriginalFilename(),file.getBytes(),StringUtils.getFilenameExtension(file.getOriginalFilename()));

        String[] upload = FastDFSUtil.upload(fastDFSFile);
        //拼接访问地址
        String url =FastDFSUtil.getTrackerInfo()+"/"+upload[0]+"/"+upload[1];

        return new Result(true, StatusCode.OK,"上传成功",url);
     }
}

Tres, prueba de carga

puesta en marcha:
Inserte la descripción de la imagen aquí

Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí

Finalmente, comparta cómo modificar la página de bienvenida:
Primero, ingrese una URL:
http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something%20
Ingrese el archivo que desea en el área central, También puede elegir fuentes, etc., y luego pegar y copiar la imagen formada en un txt, nombrarla banner.txt y colocarla en el directorio de recursos. Después de eso, puede iniciar el proyecto. Reemplace el banner cada vez que desee cambiar el grupo. El contenido en txt está bien.

Supongo que te gusta

Origin blog.csdn.net/DreamsArchitects/article/details/108621679
Recomendado
Clasificación