1. 程式人生 > >12、FastDFS 實現 圖片伺服器

12、FastDFS 實現 圖片伺服器

FastDFS實現圖片伺服器

圖片伺服器的簡介

1、儲存空間可擴充套件。
2、提供一個統一的訪問方式。

使用FastDFS,分散式檔案系統。儲存空間可以橫向擴充套件,可以實現伺服器的高可用。支援每個節點有備份機。

什麼是FastDFS

FastDFS是用c語言編寫的一款開源的分散式檔案系統。FastDFS為網際網路量身定製,充分考慮了冗餘備份、負載均衡、線性擴容等機制,並注重高可用、高效能等指標,使用FastDFS很容易搭建一套高效能的檔案伺服器叢集提供檔案上傳、下載等服務。

FastDFS架構

FastDFS架構包括Tracker serverStorage server

。客戶端請求Tracker server進行檔案上傳、下載,通過Tracker server排程最終由Storage server完成檔案上傳和下載。
Tracker server作用是負載均衡和排程,通過Tracker server在檔案上傳時可以根據一些策略找到Storage server提供檔案上傳服務。可以將tracker稱為追蹤伺服器或排程伺服器。
Storage server作用是檔案儲存,客戶端上傳的檔案最終儲存在Storage伺服器上,Storage server沒有實現自己的檔案系統而是利用作業系統 的檔案系統來管理檔案。可以將storage稱為儲存伺服器。
在這裡插入圖片描述

服務端兩個角色:
Tracker

:管理叢集,tracker也可以實現叢集。每個tracker節點地位平等。
收集Storage叢集的狀態。
Storage:實際儲存檔案
Storage分為多個組,每個組之間儲存的檔案是不同的。每個組內部可以有多個成員,組成員內部儲存的內容是一樣的,組成員的地位是一致的,沒有主從的概念。

檔案上傳的流程

在這裡插入圖片描述

客戶端上傳檔案後儲存伺服器將檔案ID返回給客戶端,此檔案ID用於以後訪問該檔案的索引資訊。檔案索引資訊包括:組名,虛擬磁碟路徑,資料兩級目錄,檔名。
在這裡插入圖片描述

  • 組名:檔案上傳後所在的storage組名稱,在檔案上傳成功後有storage伺服器返回,需要客戶端自行儲存。
  • 虛擬磁碟路徑:storage
    配置的虛擬路徑,與磁碟選項store_path*對應。如果配置了store_path0則是M00,如果配置了store_path1則是M01,以此類推。
  • 資料兩級目錄:storage伺服器在每個虛擬磁碟路徑下建立的兩級目錄,用於儲存資料檔案。
  • 檔名:與檔案上傳時不同。是由儲存伺服器根據特定資訊生成,檔名包含:源儲存伺服器IP地址、檔案建立時間戳、檔案大小、隨機數和檔案拓展名等資訊。

##3 檔案下載
在這裡插入圖片描述

最簡單的FastDFS架構

在這裡插入圖片描述

圖片伺服器安裝方法

這裡我們使用的是已經安裝好的圖片伺服器的壓縮包
在這裡插入圖片描述
步驟一:解壓縮
在這裡插入圖片描述
步驟二:把圖片伺服器新增到 VMware 中
在這裡插入圖片描述步驟三:VMware的網路配置
在這裡插入圖片描述步驟四:啟動虛擬機器
在這裡插入圖片描述移動:網路配置不發生變化。要使用圖片伺服器,需要保證網路配置不變。
複製:重新生成一塊網絡卡mac地址是新地址。

Ip地址:192.168.25.133
使用者名稱rootitcast
密碼:itcast

該虛擬機器是帶圖形介面的,輸入startx啟動圖形介面。

FastDFS相關資源:https://download.csdn.net/download/weixin_42112635/10837353

圖片上傳依賴配置新增

依賴新增

e3-common的pom.xml新增

        <!--fastdfs-->
        <dependency>
            <groupId>cn.bestwu</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27</version>
        </dependency>

圖片上傳測試

e3-manager-web :中寫測試類

package cn.ynx.e3mall.fastdfs;

import org.csource.fastdfs.*;
import org.junit.Test;

public class FastDFSTest {

    @Test
    public void testFileUpload() throws Exception {
        // 1、載入配置檔案,配置檔案中的內容就是tracker服務的地址。
        ClientGlobal.init("C:\\Users\\ys951\\Desktop\\e3mall\\e3-manager-web\\src\\main\\resources\\conf\\client.conf");
        // 2、建立一個TrackerClient物件。直接new一個。
        TrackerClient trackerClient = new TrackerClient();
        // 3、使用TrackerClient物件建立連線,獲得一個TrackerServer物件。
        TrackerServer trackerServer = trackerClient.getConnection();
        // 4、建立一個StorageServer的引用,值為null
        StorageServer storageServer = null;
        // 5、建立一個StorageClient物件,需要兩個引數TrackerServer物件、StorageServer的引用
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);
        // 6、使用StorageClient物件上傳圖片。
        //副檔名不帶“.”
        String[] strings = storageClient.upload_file("C:\\Users\\ys951\\Desktop\\02.教案-AB-3.0\\111.png", "png", null);
        // 7、返回陣列。包含組名和圖片的路徑。
        for (String string : strings) {
            System.out.println(string);
        }
    }

}

新增配置檔案:
conf/client.conf

tracker_server=192.168.25.133:22122

執行測試類,得到:

group1
M00/00/00/wKgZhVwLka6ARI-nAAdw8AHA8so639.png

瀏覽器輸入:http://192.168.25.133/group1/M00/00/00/wKgZhVwLka6ARI-nAAdw8AHA8so639.png
顯示上傳的圖片

新增上傳工具類 FastDFSClient.java

放到 e3-commoncn.ynx.e3mall.common.utils包下面

package cn.ynx.e3mall.common.utils;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

public class FastDFSClient {

	private TrackerClient trackerClient = null;
	private TrackerServer trackerServer = null;
	private StorageServer storageServer = null;
	private StorageClient1 storageClient = null;
	
	public FastDFSClient(String conf) throws Exception {
		if (conf.contains("classpath:")) {
			conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
		}
		ClientGlobal.init(conf);
		trackerClient = new TrackerClient();
		trackerServer = trackerClient.getConnection();
		storageServer = null;
		storageClient = new StorageClient1(trackerServer, storageServer);
	}
	
	/**
	 * 上傳檔案方法
	 * <p>Title: uploadFile</p>
	 * <p>Description: </p>
	 * @param fileName 檔案全路徑
	 * @param extName 副檔名,不包含(.)
	 * @param metas 檔案擴充套件資訊
	 * @return
	 * @throws Exception
	 */
	public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
		String result = storageClient.upload_file1(fileName, extName, metas);
		return result;
	}
	
	public String uploadFile(String fileName) throws Exception {
		return uploadFile(fileName, null, null);
	}
	
	public String uploadFile(String fileName, String extName) throws Exception {
		return uploadFile(fileName, extName, null);
	}
	
	/**
	 * 上傳檔案方法
	 * <p>Title: uploadFile</p>
	 * <p>Description: </p>
	 * @param fileContent 檔案的內容,位元組陣列
	 * @param extName 副檔名
	 * @param metas 檔案擴充套件資訊
	 * @return
	 * @throws Exception
	 */
	public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {
		
		String result = storageClient.upload_file1(fileContent, extName, metas);
		return result;
	}
	
	public String uploadFile(byte[] fileContent) throws Exception {
		return uploadFile(fileContent, null, null);
	}
	
	public String uploadFile(byte[] fileContent, String extName) throws Exception {
		return uploadFile(fileContent, extName, null);
	}

}

使用工具類上傳測試

    @Test
    public void testFastDfsClient() throws Exception {
        FastDFSClient fastDFSClient = new FastDFSClient("C:\\Users\\ys951\\Desktop\\e3mall\\e3-manager-web\\src\\main\\resources\\conf\\client.conf");
        String file = fastDFSClient.uploadFile("C:\\Users\\ys951\\Desktop\\02.教案-AB-3.0\\111.png");
        System.out.println(file);
    }

圖片上傳功能

功能分析

在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
使用的是 KindEditor 的多圖片上傳外掛。
KindEditor 4.x 文件
http://kindeditor.net/doc.php

在這裡插入圖片描述

請求的 url :/pic/upload
引數:MultiPartFile uploadFile
返回值:
在這裡插入圖片描述

可以建立一個pojo對應返回值。可以使用 map

業務邏輯:
1、接收頁面傳遞的圖片資訊uploadFile
2、把圖片上傳到圖片伺服器。使用封裝的工具類實現。需要取檔案的內容和副檔名。
3、圖片伺服器返回圖片的url
4、將圖片的url補充完整,返回一個完整的url。
5、把返回結果封裝到一個Map物件中返回。

1、需要把 commons-io、fileupload 的 jar 包新增到 web 工程中。

Common-io 在 common 中存在了,只要新增 fileupload

            <!-- 檔案上傳元件 -->
			<dependency>
				<groupId>commons-fileupload</groupId>
				<artifactId>commons-fileupload</artifactId>
			</dependency>

2、配置多媒體解析器

在 springmc.xml 裡面配置

    <!-- 配置多媒體解析器 -->
    <!-- 定義檔案上傳解析器 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設定預設編碼 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 設定檔案上傳的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>

編寫 Controller 接收圖片

返回的 json 資料,可以寫 pojo ,也可以寫 map 。

package cn.ynx.e3mall.controller;

import cn.ynx.e3mall.common.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Controller
public class PictureController {

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @RequestMapping("/pic/upload")
    @ResponseBody
    public Map fileUpload(MultipartFile uploadFile) {
        try {
            //1、取檔案的副檔名
            String originalFilename = uploadFile.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //2、建立一個FastDFS的客戶端
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:conf/client.conf");
            //3、執行上傳處理
            String path = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
            //4、拼接返回的url和ip地址,拼裝成完整的url
            String url = IMAGE_SERVER_URL + path;
            //5、返回map
            Map result = new HashMap<>();
            result.put("error", 0);
            result.put("url", url);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            //5、返回map
            Map result = new HashMap<>();
            result.put("error", 1);
            result.put("message", "圖片上傳失敗");
            return result;
        }
    }
}

新增配置檔案,conf 下面建一resource.properties

# 圖片伺服器的地址
IMAGE_SERVER_URL=http://192.168.25.133/

springmvc.xml 載入配置檔案

    <!-- 載入配置檔案 -->
	<context:property-placeholder location="classpath:conf/resource.properties" />

Controller 裡面用 @Value 讀取配置檔案的值

能回顯,說明上傳成功。回顯,是再從伺服器拿到圖片。

解決瀏覽器相容性的問題

KindEditor 的圖片上傳外掛,對瀏覽器相容性不好。
使用 @ResponseBody 註解返回 java 物件,
Content-Type:application/json;charset=UTF-8

返回字串時:
Content-Type:text/plain;charset=UTF-8

Common 裡面匯入
在這裡插入圖片描述
指定響應結果的content-type:
在這裡插入圖片描述
KindEditor的多圖片上傳外掛最後響應的content-type是text/plan格式的json字串。相容性是最好的。
在這裡插入圖片描述