fastDFS & SpringBoot
docker 安装 fastDFS
在服务器安装完docker环境后,搭建过程就很简单了。搭建参考:docker+fastdfs+springboot一键式搭建分布式文件服务器
搭建过程一共两步:
1. 拉取共享的fastdfs镜像
docker pull qbanxiaoli/fastdfs
2. 然后运行拉取的fastDFS镜像
docker run -d \
--restart=always \
--privileged=true \
--net=host \
--name=fastdfs \
-e IP=192.168.104.5 \
-e WEB_PORT=80 \
-v /usr/soft/fastdfs:/var/local/fdfs \
qbanxiaoli/fastdfs
IP 后面是你的服务器公网ip或者虚拟机的IP,-e WEB_PORT=80 指定nginx端口,这里不需要额外安装nginx了,fastdfs镜像里面已经包含了nginx了,启动镜像后,nginx已经启动了。如果宿主机上有项目占用了80端口,这里应该会启动失败。
这时访问上面用到的IP:192.168.104.5,应该显示nginx的欢迎页。
另外一种测试方法,直接进入docker镜像内部,使用命令,上传一个html文件。
首先进入fastdfs镜像内部:
docker exec -it fastdfs /bin/bash
新建index.html 文件:
echo "Hello FastDFS!">index.html
上传文件:
fdfs_test /etc/fdfs/client.conf upload index.html
如果返回一个URL则表示fastdfs可正常使用。
如果这里显示不出来nginx的欢迎页,则需要检查下防火墙是否开启80端口,否则后面使用fastdfs文件服务器上传文件后,返回的文件的URL是打不开的。
另外还需要开放22122和23000端口,否则在程序中还是无法使用fastdfs的,因为fastDFS内部的跟踪服务器tracker_server需要依赖22122端口,而23000端口是存储服务器storage_server依赖的端口。如果没有开放这俩端口,程序可能会报异常:ERROR - file: connection_pool.c, line: 130, connect to IP:23000 fail
centos 7 操作防火墙:
查看防火墙状态:systemctl status firewalld
开启或者关闭防火墙:systemctl start firewalld 关闭修改start为stop
查看开放端口列表:firewall-cmd --list-ports
开放固定端口:firewall-cmd --zone=public --add-port=22122/tcp --permanent
命令含义: --zone #作用域 --add-port=80/tcp #添加端口,格式为:端口/通讯协议 --permanent #永久生效,没有此参数重启后失效
开启后需要重启防火墙才生效 :firewall-cmd --reload
如果为低版本的Linux系统,开放防火墙端口,可以使用:iptables -I INPUT -p tcp --dport 22122 -j ACCEPT开放端口。
我这里开放22122和23000端口是正常的,但是开放80端口虽然成功了,但是上面列表里面却不显示80端口,nginx的欢迎页页正常显示出来了。上传图片文件返回的地址也是可以访问的。
Springboot集成fastDFS
添加maven依赖,这里我是用的是
加入依赖
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.7</version>
</dependency>
在SpringBoot启动类上面添加:
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
FastDFSClient工具类:FastDFSClient.java,如果使用的是低版本的,工具类里面会提示方法或者包找不到,可能要调整下工具类里面的包路径,jar包里面的文件不多,如果显示找不到该包,则可以去看下是不是不同版本的包结构有所变化。1.26.7和1.26.2的包结构就有所调整,好在我看下源码包里面的文件,给调整了下import的路径。
package gc.cnnvd.framework.common;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
/**
* FastDFSClient工具类
* @Auther linmengmeng
* @Date 2021-04-01
*/
@Component
public class FastDFSClient {
private static Logger log = LoggerFactory.getLogger(FastDFSClient.class);
private static FastFileStorageClient fastFileStorageClient;
private static FdfsWebServer fdfsWebServer;
@Autowired
public void setFastDFSClient(FastFileStorageClient fastFileStorageClient, FdfsWebServer fdfsWebServer) {
FastDFSClient.fastFileStorageClient = fastFileStorageClient;
FastDFSClient.fdfsWebServer = fdfsWebServer;
}
/**
* @param multipartFile 文件对象
* @return 返回文件地址
* @description 上传文件
*/
public static String uploadFile(MultipartFile multipartFile) {
try {
StorePath storePath = fastFileStorageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), FilenameUtils.getExtension(multipartFile.getOriginalFilename()), null);
return storePath.getFullPath();
} catch (IOException e) {
log.error(e.getMessage());
return null;
}
}
/**
* @param multipartFile 图片对象
* @return 返回图片地址
* @description 上传缩略图
*/
public static String uploadImageAndCrtThumbImage(MultipartFile multipartFile) {
try {
StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(multipartFile.getInputStream(), multipartFile.getSize(), FilenameUtils.getExtension(multipartFile.getOriginalFilename()), null);
return storePath.getFullPath();
} catch (Exception e) {
log.error(e.getMessage());
return null;
}
}
/**
* @param file 文件对象
* @return 返回文件地址
* @description 上传文件
*/
public static String uploadFile(File file) {
try {
FileInputStream inputStream = new FileInputStream(file);
StorePath storePath = fastFileStorageClient.uploadFile(inputStream, file.length(), FilenameUtils.getExtension(file.getName()), null);
return storePath.getFullPath();
} catch (Exception e) {
log.error(e.getMessage());
return null;
}
}
/**
* @param file 图片对象
* @return 返回图片地址
* @description 上传缩略图
*/
public static String uploadImageAndCrtThumbImage(File file) {
try {
FileInputStream inputStream = new FileInputStream(file);
StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(inputStream, file.length(), FilenameUtils.getExtension(file.getName()), null);
return storePath.getFullPath();
} catch (Exception e) {
log.error(e.getMessage());
return null;
}
}
/**
* @param bytes byte数组
* @param fileExtension 文件扩展名
* @return 返回文件地址
* @description 将byte数组生成一个文件上传
*/
public static String uploadFile(byte[] bytes, String fileExtension) {
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
StorePath storePath = fastFileStorageClient.uploadFile(stream, bytes.length, fileExtension, null);
return storePath.getFullPath();
}
/**
* @param fileUrl 文件访问地址
* @param file 文件保存路径
* @description 下载文件
*/
public static boolean downloadFile(String fileUrl, File file) {
try {
StorePath storePath = StorePath.parseFromUrl(fileUrl);
byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
FileOutputStream stream = new FileOutputStream(file);
stream.write(bytes);
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
return true;
}
/**
* @param fileUrl 文件访问地址
* @description 删除文件
*/
public static boolean deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
return false;
}
try {
StorePath storePath = StorePath.parseFromUrl(fileUrl);
fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
return true;
}
/**
* 封装文件完整URL地址
* @param path
* @return
*/
public static String getResAccessUrl(String path) {
String url = fdfsWebServer.getWebServerUrl() + path;
log.info("上传文件地址为:{}", url);
return url;
}
}
配置文件,直接粘贴的上面博客里面的配置文件,我这里对配置文件拆分了,贴出来会有些乱。
# 分布式文件系统fastdfs配置
fdfs:
# socket连接超时时长
soTimeout: 1500
# 连接tracker服务器超时时长
connectTimeout: 600
pool:
# 从池中借出的对象的最大数目
max-total: 153
# 获取连接时的最大等待毫秒数100
max-wait-millis: 102
# 缩略图生成参数,可选
thumbImage:
width: 150
height: 150
# 跟踪服务器tracker_server请求地址,支持多个,这里只有一个,如果有多个在下方加- x.x.x.x:port
trackerList:
- 192.168.127.131:22122
#
# 存储服务器storage_server访问地址
web-server-url: http://192.168.127.131/
spring:
http:
multipart:
max-file-size: 100MB # 最大支持文件大小
max-request-size: 100MB # 最大支持请求大小
测试类:
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import gc.cnnvd.SpringBootPlusApplication;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootApplication.class)
public class BaseTest {
protected final static Log log = LogFactory.get(BaseTest.class);
}
import gc.cnnvd.framework.common.FastDFSClient;
import org.junit.Test;
import java.io.File;
/**
* @Auther linmengmeng
* @Date 2021-04-01 15:42
*/
public class FastDFSTest extends BaseTest{
@Test
public void upload(){
// String fileUrl = this.getClass().getResource("/test.jpg").getPath();
String fileUrl = "C:\\Users\\16322\\Desktop\\only-one.jpg";
File file = new File(fileUrl);
String str = FastDFSClient.uploadFile(file);
String resAccessUrl = FastDFSClient.getResAccessUrl(str);
System.out.println(resAccessUrl);
}
}
上传成功,会显示下图:
如果服务器的22122或者23000端口没有开放,则会上传失败,控制台会有明显的提示。
这时,复制链接到浏览器里面,可正常显示图片内容
: