【FastDFS】2_FastDFS 实战微服务

Eureka 注册中心

具体如何搭建,可参考https://blog.csdn.net/XJ0927/article/details/109404290,这里搭建单机版的就行,重点是使用我们的 FastDFS 进行文件上传和下载 。

微服务 upload-service

本模块是直接在父项目 [ spring_cloud_yang ] 下创建,这里将父项目 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">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>spring_cloud_yang</artifactId>
  <version>1.0-SNAPSHOT</version>
  <modules>
      <module>cloud-eureka-server7001</module>
      <module>upload_service</module>
  </modules>
  <!--总父工程-->
  <packaging>pom</packaging>

    <!--统一管理jar包和版本-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.18.2</lombok.version>
        <mysql.version>8.0.18</mysql.version>
        <druid.verison>1.1.16</druid.verison>
        <mybatis.spring.boot.verison>1.3.0</mybatis.spring.boot.verison>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!--spring boot 2.2.2-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud Hoxton.SR1-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud alibaba 2.1.0.RELEASE-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- MySql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <!-- Druid -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>${druid.verison}</version>
            </dependency>
            <!-- mybatis-springboot整合 -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.spring.boot.verison}</version>
            </dependency>
            <!--lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <!-- log4j -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <!--热部署需要的插件-->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

1、新建 Module : upload-service

2、改 POM

引入:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--eureka client:调用想入驻注册中心也是客户端的身份 client-->
<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>
    <version>1.26.7</version>
</dependency>

完整版:[ 其他依赖自行添加 ]

<?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>spring_cloud_yang</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>upload_service</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!--eureka client:调用想入驻注册中心也是客户端的身份 client-->
        <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>
            <version>1.26.7</version>
        </dependency>
        
    </dependencies>
</project>

3、建 YML

server:
  port: 9004

spring:
  application:
    name:  upload-service
  servlet:
    multipart:
      enabled: true
      max-file-size: 10MB #单个文件上传大小
      max-request-size: 20MB #总文件上传大小
fdfs:
  connect-timeout: 60 # 链接超时
  so-timeout: 60 # 读取时间
  thumb-image: # 生成缩略图参数
    height: 150
    width: 150
  tracker-list: 192.168.77.138:22122

eureka:
  client:
    service-url:
       defaultZone: http://eureka7001.com:7001/eureka/
  instance:
#    prefer-ip-address: true  #更倾向于使用ip地址,而不是主机名
#    ip-address: eureka7001.com  #ip地址
    lease-renewal-interval-in-seconds: 5  #续约间隔,默认30秒
    lease-expiration-duration-in-seconds: 5 #服务的实效时间, 默认90秒

4、启动类

@SpringBootApplication
@EnableDiscoveryClient
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

5、配置类

@Configuration
@Import(FdfsClientConfig.class)
public class DfsConfig {

}

6、工具类 FileDfsUtil

调用 fastdfs-client 工具方法实现文件上传和删除

package com.xj0927.util;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author: xj0927
 * @Description:
 * @Date Created in 2020-11-14 15:25
 * @Modified By:
 */
@Component
public class FileDfsUtil {

    @Resource
    private FastFileStorageClient storageClient;

    /**
     * @Description: 上传文件
     * @Param:
     * @Return:
     * @Author: xj0927
     * @Date Created in 2020/11/14 15:26
     */
    public String upload(MultipartFile multipartFile) throws IOException {
       
        //源文件名
        String filename = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
        // [输入流,文件大小,文件名,作者名]
        StorePath storePath = storageClient.uploadImageAndCrtThumbImage(multipartFile.getInputStream(), multipartFile.getSize(), filename, null);
        //返回类似 [/group1/M00/00/00/wKhIgl0n4AKABxQEABhlMYw_3Lo825.png]
       return storePath.getFullPath();
    }

    /**
    * @Description: 删除文件
    * @Param:
    * @Return:
    * @Author: xj0927
    * @Date Created in 2020/11/14 15:29
    */
    public void deleteFile(String fileUrl){
        //得到传入的 [/group1/M00/00/00/wKhIgl0n4AKABxQEABhlMYw_3Lo825.png]
        StorePath storePath = StorePath.parseFromUrl(fileUrl);
        // [ group1,/M00/00/00/wKhIgl0n4AKABxQEABhlMYw_3Lo825.png]
        storageClient.deleteFile(storePath.getGroup(),storePath.getPath());
    }

}

7、Controll 类

创建文件上传和删除功能的 controller,实现文件删除

/**
 * @Author: xj0927
 * @Description: 上传文件
 * @Modified By:
 */
@RestController
public class FileController {
    
    @Resource
    private FileDfsUtil fileDfsUtil;
	
    //[请求,Post方式,头信息]
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        String result ;
        try {
            String path = fileDfsUtil.upload(file);
            if (StringUtils.isEmpty(path)) {
                result = "上传失败";
            } else {
                result = path;
            }
        } catch (IOException e) {
            e.printStackTrace();
            result = "服务器异常";
        }
        return ResponseEntity.ok(result);
    }

    /**
    *  删除文件
    */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public ResponseEntity<String> delete(String fileName) {
        fileDfsUtil.deleteFile(fileName);
        return ResponseEntity.ok("success");
    }
}

8、测试

此时是采用 Post 请求,使用工具 Postman 进行访问,不能使用浏览器 。

上传

在这里插入图片描述

同时我们进入 Storage 容器的存放文件的目录下

/data/fast_data/data/00/00

在这里插入图片描述

便有我们上传的文件了!!!

访问

现在可以使用浏览器进行资源的访问

http://192.168.77.138:8080/group1/M00/00/00/wKhNil-wIxiALpETACwR9_-d1HQ323.PNG

在这里插入图片描述

删除

在这里插入图片描述

再进行查看时,

在这里插入图片描述

只有缩略版的图片了 。


踩 坑 记 录 : \color{red}{踩坑记录:} 若出现

java.net.SocketTimeoutException: connect timed out
	at java.base/java.net.PlainSocketImpl.waitForConnect(Native Method) ~[na:na]
	at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:107) ~[na:na]
	at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
	.....

解决办法: 要不就开启相应的端口,要不关掉防火墙

具体如何关闭及设置开启端口,参照:https://blog.csdn.net/XJ0927/article/details/109607983

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值