SpringBoot学习:整合FastDFS

发布于 2019-03-01  6340 次阅读


FastDFS安装参考前一篇文章: FastDFS文件服务器安装配置

FastDFS-Client使用方式
1.在项目Pom当中加入依赖
Maven依赖为

<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.26.2</version>
</dependency>

2.将Fdfs配置引入项目
FastDFS-Client客户端引入本地化项目的方式非常简单,在SpringBoot项目/src/[com.xxx.主目录]/conf当中配置

@SpringBootApplication
@EnableCaching
@MapperScan("com.example.demo.mapper")
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}


对的,只需要一行注解 @Import(FdfsClientConfig.class)就可以拥有带有连接池的FastDFS Java客户端了。

如果不加 spring.jmx.enabled=false 和 @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) 启动项目时会报异常: 

org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [FdfsConnectionPool [maxTotal=50, blockWhenExhausted=true, maxWaitMillis=100, lifo=true, fairness=false, testOnCreate=false, testOnBorrow=false, testOnReturn=false, testWhileIdle=true, timeBetweenEvictionRunsMillis=60000, numTestsPerEvictionRun=-1, minEvictableIdleTimeMillis=180000, softMinEvictableIdleTimeMillis=-1, evictionPolicy=org.apache.commons.pool2.impl.DefaultEvictionPolicy@1a05ff8e, closeLock=java.lang.Object@251e2f4a, closed=false, evictionLock=java.lang.Object@1abea1ed, evictor=org.apache.commons.pool2.impl.BaseGenericObjectPool$Evictor@6f5288c5, evictionIterator=null, factoryClassLoader=java.lang.ref.WeakReference@5a9ef32e, oname=org.apache.commons.pool2:type=GenericKeyedObjectPool,name=pool, creationStackTrace=java.lang.Exception
	at org.apache.commons.pool2.impl.BaseGenericObjectPool.<init>(BaseGenericObjectPool.java:142)
	at org.apache.commons.pool2.impl.GenericKeyedObjectPool.<init>(GenericKeyedObjectPool.java:105)
	at com.github.tobato.fastdfs.conn.FdfsConnectionPool.<init>(FdfsConnectionPool.java:33)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)

注意:@EnableMBeanExport解决问题JMX重复注册问题,不要再配置 spring.jmx.enabled=false,以免影响SpringBoot默认的JMX监控。

3.在application.yml当中配置Fdfs相关参数

===================

分布式文件系统FDFS配置

===================

fdfs:
so-timeout: 1501
connect-timeout: 601
thumb-image: #缩略图生成参数
width: 150
height: 150
tracker-list: #TrackerList参数,支持多个
- 192.168.1.105:22122

作者:super彦
来源:CSDN
原文:https://blog.csdn.net/ityqing/article/details/81384740
版权声明:本文为博主原创文章,转载请附上博文链接!

FastDFS工具类

package com.example.demo.util;


import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.github.tobato.fastdfs.service.TrackerClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

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

@Component
public class FastDFSUtil {

    //分布式文件系统IP
    @Value("${fastdfs.host}")
    public String fastDFSHost;
    //分布式文件系统端口
    @Value("${fastdfs.port}")
    public String fastDFSPort;
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private TrackerClient trackerClient;
    private final Logger logger = LoggerFactory.getLogger(FastDFSUtil.class);

    /**
     * 文件上传
     */
    public String upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        long size = file.getSize();
        StorePath storePath = fastFileStorageClient.uploadFile(inputStream,size,fileName.substring(fileName.lastIndexOf(".")+1),null);

       // StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
       return getResAccessUrl(storePath);
    }

    /**
     * 下载文件
     * @param fileUrl
     * @return
     * @throws IOException
     */
    public byte[] downloadFile(String fileUrl) throws IOException {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = fastFileStorageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }

    /**
     * 测试文件删除
     */
    public void deleteFile(){
        fastFileStorageClient.deleteFile("group1","M00/00/00/wKiAjVlpQVyARpQwAADGA0F72jo566.jpg");
    }
    // 封装文件完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = storePath.getFullPath();
        return fileUrl;
    }
}

个人博客,用于记录工作日常的问题。