SpringCloud使用FastDFS

SpringCloud使用FastDFS

上傳文件微服務模塊結構

在這裏插入圖片描述

配置文件

  1. pom.xml----->引入fastdfs依賴(在父工程下引入了版本信息, 所以在該微服務下, 不用引入版本信息)

    <dependency>
        <groupId>com.github.tobato</groupId>
        <artifactId>fastdfs-client</artifactId>
        <version>1.26.1-RELEASE<ersion>
    </dependency>
    
  2. pom.xml----->該上傳文件微服務全部依賴

    <?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>leyou</artifactId>
            <groupId>com.leyou.parent</groupId>
            <version>1.0.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.leyou.service</groupId>
        <artifactId>ly-upload</artifactId>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
    
            <!-- 引入fastdfs客戶端 -->
            <dependency>
                <groupId>com.github.tobato</groupId>
                <artifactId>fastdfs-client</artifactId>
            </dependency>
    
            <!-- 引用test啓動器 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
            </dependency>
    
            <dependency>
                <groupId>com.leyou.common</groupId>
                <artifactId>ly-common</artifactId>
                <version>1.0.0-SNAPSHOT</version>
            </dependency>
    
        </dependencies>
    
    
    </project>
    
  3. application.yml----->配置fastdfs

    fdfs:
      # 請求超時時間
      so-timeout: 1501
      # 連接超時時間
      connect-timeout: 601
      thumb-image: # 縮略圖, (可以自由配置, 這裏只是爲了加載快)
        width: 60
        height: 60
      tracker-list: # tracker地址
        - 192.168.79.128:22122
    
  4. application.yml----->該上傳文件微服務全部配置

    server:
      port: 8083
    spring:
      application:
        name: upload-service
      servlet:
        multipart:
          max-file-size: 5MB # 限制文件上傳的大小
    # Eureka
    eureka:
      client:
        service-url:
          defaultZone: http://127.0.0.1:10086/eureka
      instance:
        lease-renewal-interval-in-seconds: 5 # 每隔5秒發送一次心跳
        lease-expiration-duration-in-seconds: 10 # 10秒不發送就過期
        prefer-ip-address: true
        ip-address: 127.0.0.1
        instance-id: ${spring.application.name}:${server.port}
    fdfs:
      # 請求超時時間
      so-timeout: 1501
      # 連接超時時間
      connect-timeout: 601
      thumb-image: # 縮略圖, (可以自由配置, 這裏只是爲了加載快)
        width: 60
        height: 60
      tracker-list: # tracker地址
        - 192.168.79.128:22122
    
    # 配置文件上傳的域名
    ly:
      upload:
        baseUrl: http://image.leyou.com/
        allowTypes:
          - image/jpeg
          - image/png
    

啓動類

  1. UploadApplication

    package com.leyou.upload;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
    /**
     * @program: leyou
     * @description:
     * @author: Mr.Xiao
     * @create: 2020-05-27 19:04
     **/
    @SpringBootApplication
    @EnableDiscoveryClient
    public class UploadApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(UploadApplication.class);
        }
    
    }
    

Config

  1. FastClientImporter------>fastdfs客戶端

    package com.leyou.upload.config;
    
    import com.github.tobato.fastdfs.FdfsClientConfig;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableMBeanExport;
    import org.springframework.context.annotation.Import;
    import org.springframework.jmx.support.RegistrationPolicy;
    
    @Configuration
    @Import(FdfsClientConfig.class)
    // 解決jmx重複註冊bean的問題
    @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
    public class FastClientImporter {
    }
    
  2. UploadProperties------->java配置類

    package com.leyou.upload.config;
    
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    import java.util.List;
    
    /**
     * @program: leyou
     * @description:
     * @author: Mr.Xiao
     * @create: 2020-05-28 18:07
     **/
    
    @Data
    @Component
    @ConfigurationProperties(prefix = "ly.upload")
    public class UploadProperties {
    
        private String baseUrl;
        private List<String> allowTypes;
    
    }
    
    

Controller

  1. UploadController

    package com.leyou.upload.web;
    
    import com.leyou.common.enums.ExceptionEnum;
    import com.leyou.common.exception.LyException;
    import com.leyou.upload.service.UploadService;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    /**
     * @program: leyou
     * @description:
     * @author: Mr.Xiao
     * @create: 2020-05-28 09:31
     **/
    @RestController
    @RequestMapping("/upload")
    public class UploadController {
    
        @Autowired
        private UploadService uploadService;
    
        @PostMapping("/image")
        public ResponseEntity<String> uploadImage (@RequestParam("file") MultipartFile file) {
            String url = uploadService.uploadImage(file);
    
            if (StringUtils.isBlank(url)) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
    
            return ResponseEntity.status(HttpStatus.CREATED).body(url);
        }
    
    }
    
    

Service

  1. UploadService接口

    package com.leyou.upload.service;
    
    import org.springframework.web.multipart.MultipartFile;
    
    /**
     * @program: leyou
     * @description: 表現層上傳文件
     * @author: Mr.Xiao
     * @create: 2020-05-28 09:53
     **/
    public interface UploadService {
        /**
         * 上傳圖片
         * @param file
         * @return
         */
        String uploadImage(MultipartFile file);
    
    }
    
  2. UploadServiceImpl實體類

    package com.leyou.upload.service.impl;
    
    import com.github.tobato.fastdfs.domain.StorePath;
    import com.github.tobato.fastdfs.service.FastFileStorageClient;
    import com.leyou.upload.config.UploadProperties;
    import com.leyou.common.enums.ExceptionEnum;
    import com.leyou.common.exception.LyException;
    import com.leyou.upload.service.UploadService;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    
    /**
     * @program: leyou
     * @description: 業務層 上傳圖片實現類
     * @author: Mr.Xiao
     * @create: 2020-05-28 09:54
     **/
    @Service("uploadService")
    @Slf4j
    @EnableConfigurationProperties(UploadProperties.class) // 引入配置類
    public class UploadServiceImpl implements UploadService {
    
        @Autowired  // 注入fastdfs上傳文件bean
        private FastFileStorageClient fastFileStorageClient;
    
        @Autowired
        private UploadProperties uploadProperties;
    
        /**
         * 上傳圖片
         * @param file
         * @return
         */
        @Override
        public String uploadImage(MultipartFile file) {
            try {
                // 校驗文件
                String type = file.getContentType();
                // 判斷文件是否在這個類型裏面
                if (!uploadProperties.getAllowTypes().contains(type)) {
                    throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
                }
    
                // 校驗內容
                BufferedImage imageContent = ImageIO.read(file.getInputStream());
                // 爲null不是圖片
                if (imageContent == null) {
                    throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
                }
    
                // 將文件上傳到FastDFS
                // 獲取文件後綴
                String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
                /*
                    第一個參數: 上傳文件流
                    第二個參數: 文件大小
                    第三個參數: 文件後綴
                    第四個參數: set集合, 可以直接用null
                 */
                StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
    
                // 返回路徑 , 帶group的
                return uploadProperties.getBaseUrl() + storePath.getFullPath();
    
            } catch (IOException e) {
                // 上傳失敗
                log.error("[文件上傳] 上傳文件失敗!", e);
                throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
            }
    
    
        }
    }
    
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章