SpringBoot2整合FastDFS中間件,實(shí)現(xiàn)文件分布式管理

本文源碼:GitHub·點(diǎn)這里 || GitEE·點(diǎn)這里

成都創(chuàng)新互聯(lián)公司于2013年創(chuàng)立,先為常州等服務(wù)建站,常州等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為常州企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。

一、FastDFS簡(jiǎn)介

1、FastDFS作用

FastDFS是一個(gè)開源的輕量級(jí)分布式文件系統(tǒng),它對(duì)文件進(jìn)行管理,功能包括:文件存儲(chǔ)、文件同步、文件上傳、文件下載等,解決了大容量存儲(chǔ)和負(fù)載均衡的問(wèn)題。

安裝連接:

安裝流程詳解

2、核心角色

FastDFS是由跟蹤服務(wù)器(trackerserver)、存儲(chǔ)服務(wù)器(storageserver)和客戶端(client)三個(gè)部分組成。

1)跟蹤服務(wù)器

FastDFS的協(xié)調(diào)者,負(fù)責(zé)管理所有的storage server和group,每個(gè)storage在啟動(dòng)后會(huì)連接Tracker,告知自己所屬的group等信息,并保持周期性的心跳,tracker根據(jù)storage的心跳信息,建立group到[storage server list]的映射表。

2)存儲(chǔ)服務(wù)器

以組(group)為單位,一個(gè)group內(nèi)包含多臺(tái)storage機(jī)器,數(shù)據(jù)互為備份,存儲(chǔ)空間以group內(nèi)容量最小的storage為準(zhǔn),所以建議group內(nèi)的多個(gè)storage盡量配置相同,以免造成存儲(chǔ)空間的浪費(fèi)。

3)客戶端

業(yè)務(wù)請(qǐng)求的發(fā)起方,通過(guò)專有接口,使用TCP/IP協(xié)議與跟蹤器服務(wù)器或存儲(chǔ)節(jié)點(diǎn)進(jìn)行數(shù)據(jù)交互。

3、運(yùn)轉(zhuǎn)流程

1、存儲(chǔ)服務(wù)定時(shí)向跟蹤服務(wù)上傳狀態(tài)信息;
2、客戶端發(fā)起請(qǐng)求;
3、跟蹤器同步存儲(chǔ)器狀態(tài),返回存儲(chǔ)服務(wù)端口和IP;
4、客戶端執(zhí)行文件操作(上傳,下載)等。

二、與SpringBoot2整合

1、核心步驟

1)、配置FastDFS執(zhí)行環(huán)境
2)、文件上傳配置
3)、整合Swagger2測(cè)試接口

2、核心依賴

<!-- FastDFS依賴 -->
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.26.5</version>
</dependency>
<!-- Swagger2 核心依賴 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

3、配置FastDFS

0) 核心配置文件

fdfs:
  # 鏈接超時(shí)
  connect-timeout: 60
  # 讀取時(shí)間
  so-timeout: 60
  # 生成縮略圖參數(shù)
  thumb-image:
    width: 150
    height: 150
  tracker-list: 192.168.72.130:22122

1) 核心配置類

@Configuration
@Import(FdfsClientConfig.class)
// Jmx重復(fù)注冊(cè)bean的問(wèn)題
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class DfsConfig {
}

2)文件工具類

@Component
public class FileDfsUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileDfsUtil.class);
    @Resource
    private FastFileStorageClient storageClient ;
    /**
     * 上傳文件
     */
    public String upload(MultipartFile multipartFile) throws Exception{
        String originalFilename = multipartFile.getOriginalFilename().
                                  substring(multipartFile.getOriginalFilename().
                                  lastIndexOf(".") + 1);
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                              multipartFile.getInputStream(),
                              multipartFile.getSize(),originalFilename , null);
        return storePath.getFullPath() ;
    }
    /**
     * 刪除文件
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            LOGGER.info("fileUrl == >>文件路徑為空...");
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            LOGGER.info(e.getMessage());
        }
    }
}

4、文件上傳配置

spring:
  application:
    name: ware-fast-dfs
  servlet:
    multipart:
      enabled: true
      max-file-size: 10MB
      max-request-size: 20MB

5、配置Swagger2

主要用來(lái)生成文件上傳的測(cè)試界面。

1)配置代碼類

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.fast.dfs"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot利用Swagger構(gòu)建API文檔")
                .description("使用RestFul風(fēng)格, 創(chuàng)建人:知了一笑")
                .termsOfServiceUrl("https://github.com/cicadasmile")
                .version("version 1.0")
                .build();
    }
}

2)啟動(dòng)類注解

@EnableSwagger2

三、演示案例

1、接口代碼

@RestController
public class FileController {
    @Resource
    private FileDfsUtil fileDfsUtil ;
    /**
     * 文件上傳
     */
    @ApiOperation(value="上傳文件", notes="測(cè)試FastDFS文件上傳")
    @RequestMapping(value = "/uploadFile",headers="content-type=multipart/form-data", method = RequestMethod.POST)
    public ResponseEntity<String> uploadFile (@RequestParam("file") MultipartFile file){
        String result ;
        try{
            String path = fileDfsUtil.upload(file) ;
            if (!StringUtils.isEmpty(path)){
                result = path ;
            } else {
                result = "上傳失敗" ;
            }
        } catch (Exception e){
            e.printStackTrace() ;
            result = "服務(wù)異常" ;
        }
        return ResponseEntity.ok(result);
    }
    /**
     * 文件刪除
     */
    @RequestMapping(value = "/deleteByPath", method = RequestMethod.GET)
    public ResponseEntity<String> deleteByPath (){
        String filePathName = "group1/M00/00/00/wKhIgl0n4AKABxQEABhlMYw_3Lo825.png" ;
        fileDfsUtil.deleteFile(filePathName);
        return ResponseEntity.ok("SUCCESS") ;
    }
}

2、執(zhí)行流程

1、訪問(wèn)http://localhost:7010/swagger-ui.html測(cè)試界面
2、調(diào)用文件上傳接口,拿到文件在FastDFS服務(wù)的路徑
3、瀏覽器訪問(wèn):http://192.168.72.130/group1/M00/00/00/wKhIgl0n4AKABxQEABhlMYw_3Lo825.png
4、調(diào)用刪除接口,刪除服務(wù)器上圖片
5、清空瀏覽器緩存,再次訪問(wèn)圖片Url,回返回404

四、源代碼地址

GitHub地址:知了一笑
https://github.com/cicadasmile/middle-ware-parent
碼云地址:知了一笑
https://gitee.com/cicadasmile/middle-ware-parent

SpringBoot2 整合 FastDFS 中間件,實(shí)現(xiàn)文件分布式管理

當(dāng)前名稱:SpringBoot2整合FastDFS中間件,實(shí)現(xiàn)文件分布式管理
標(biāo)題路徑:http://muchs.cn/article36/jojisg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開發(fā)、App開發(fā)、用戶體驗(yàn)、網(wǎng)站內(nèi)鏈、營(yíng)銷型網(wǎng)站建設(shè)網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁(yè)設(shè)計(jì)