一、FastDFS简介
FastDFS是一个开源的轻量级,它对文件进行管理,功能包括:文件存储、文件同步、文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。特别适合以文件为载体的在线服务,如相册网站、视频网站等等。
FastDFS为互联网量身定制,充分考虑了冗余备份、负载均衡、线性扩容等机制,并注重高可用、高性能等指标,使用FastDFS很容易搭建一套高性能的文件服务器集群提供文件上传、下载等服务。
FastDFS 架构包括 Tracker server 和 Storage server。客户端请求 Tracker server 进行文件上传、下载,通过Tracker server 调度最终由 Storage server 完成文件上传和下载。
Tracker server 作用是负载均衡和调度,通过 Tracker server 在文件上传时可以根据一些策略找到Storage server 提供文件上传服务。可以将 tracker 称为追踪服务器或调度服务器。Storage server 作用是文件存储,客户端上传的文件最终存储在 Storage 服务器上,Storageserver 没有实现自己的文件系统而是利用操作系统的文件系统来管理文件。可以将storage称为存储服务器。
二、代码
在changgou-service模块下创建changgou-service-file子模块。
1.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">
<parent>
<artifactId>mychanggou-service</artifactId>
<groupId>com.mychanggou</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mycahnggou-service-file</artifactId>
<dependencies>
<!-- FastDFS -->
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>
<dependency>
<groupId>com.mychanggou</groupId>
<artifactId>mychanggou-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
2.主启动类
package com.mychanggou;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @author :LiuShihao
* @date :Created in 2020/9/17 8:20 下午
* @desc :
* 启动报错 : 没有数据库信息配置, 因为不需要用到数据库,所以排除数据库自动加载
*/
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableEurekaClient
public class FileApplication {
public static void main(String[] args) {
SpringApplication.run(FileApplication.class);
}
}
3.FastDFS的配置文件信息
在resources文件夹下新建fdfs_client.conf
connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.tracker_http_port = 80
tracker_server = 116.62.13.104:22122
4.文件信息封装
文件上传一般都有文件的名字、文件的内容、文件的扩展名、文件的md5值、文件的作者等相关属性,我们可以创建一个对象封装这些属性
package com.mychanggou.file;
import lombok.Data;
/**
* @author :LiuShihao
* @date :Created in 2020/9/17 8:24 下午
* @desc :
* 封装文件上传信息
* 时间:
* Author:
* type:
* size:
* 附加信息:
*/
@Data
public class FastDFSFile {
//文件名字
private String name;
//文件内容
private byte[] content;
//文件扩展名
private String ext;
//文件MD5摘要值
private String md5;
//文件创建作者
private String author;
public FastDFSFile(String name, byte[] content, String ext, String height,String width, String author) {
super();
this.name = name;
this.content = content;
this.ext = ext;
this.author = author;
}
public FastDFSFile(String name, byte[] content, String ext) {
super();
this.name = name;
this.content = content;
this.ext = ext;
}
}
5.封装FastDFS工具类
package com.mychanggou.util;
import com.mychanggou.file.FastDFSFile;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author :LiuShihao
* @date :Created in 2020/9/17 8:29 下午
* @desc :实现文件管理
* 文件上传
* 文件下载
* 文件删除
* 文件信息获取
* Storage信息获取
* Tracker信息获取
*
*
*/
public class FastDFSUtil {
//加载Tracker连接信息
static {
try {
//String fdfsconfpath = "/Users/LiuShihao/IdeaProjects/mychanggou/mychanggou-service/mycahnggou-service-file/src/main/resources/fdfs_client.conf";
//查找classpath下的文件的路径
String path = new ClassPathResource("fdfs_client.conf").getPath();
ClientGlobal.init(path);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 文件上传
* @param fastDFSFile 上传的文件信息封装
*/
public static String[] upload(FastDFSFile fastDFSFile) throws Exception {
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = getStorageClient(trackerServer);
/**
* 通过StorageClient访问Storage,实现文件上传,并获取文件上传后的存储信息
* 1.上传文件的字节数组
* 2. 上传文件的扩展名
* 3. 上传文件的附加信息
*/
//附加信息: 创建文件附加信息 可以用于文件上传的第三个参数 比如 Author:lsh 拍摄地址:上海 拍摄终端:iPhone 11 Pro Max
// NameValuePair[] meta_list = new NameValuePair[1];
// meta_list[0] = new NameValuePair("name",fastDFSFile.getAuthor());
String[] upload = storageClient.upload_file(fastDFSFile.getContent(), fastDFSFile.getExt(), null);
/**
* upload_file返回参数:upload[]
* 1. upload[0]:文件上传所存储的组名 group1
* 2. upload[1]:文件存储到Storage上的文件名字 M00/02/14/wyt.jpg
* 也可以获得StorageClient1客户端 直接使用upload_file1 方法
*/
return upload;
}
/**
* 获取文件信息
* @param groupName group1
* @param remoteFileName M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg
* @return
* @throws Exception
*/
public static FileInfo getFileInfo(String groupName, String remoteFileName) throws Exception {
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = getStorageClient(trackerServer);
return storageClient.get_file_info(groupName,remoteFileName);
}
/**
* 下载文件
* @param groupName
* @param remoteFileName
* @return
* @throws Exception
*/
public static InputStream downloadFile(String groupName, String remoteFileName)throws Exception{
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = getStorageClient(trackerServer);
//文件下载
byte[] bytes = storageClient.download_file(groupName, remoteFileName);
return new ByteArrayInputStream(bytes);
}
/**
* 删除文件
* @param groupName
* @param remoteFileName
* @throws Exception
*/
public static void deleteFile(String groupName, String remoteFileName)throws Exception{
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = getStorageClient(trackerServer);
//文件删除
storageClient.delete_file(groupName,remoteFileName);
}
public static String getTrackerInfo()throws Exception{
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = getStorageClient(trackerServer);
//获取Tracker的端口
String hostString = trackerServer.getInetSocketAddress().getHostString();
int tracker_http_port = ClientGlobal.getG_tracker_http_port();
String url = "http://"+hostString+":"+tracker_http_port;
return url;
}
/**
* 获取TeackerServer
* @return
* @throws IOException
*/
public static TrackerServer getTrackerServer() throws IOException {
//创建一个Tracker访问的客户端对象TrackerClient
TrackerClient trackerClient = new TrackerClient();
//通过TrackerClient访问TrackerServer服务,获取连接信息
TrackerServer trackerServer = trackerClient.getConnection();
return trackerServer;
}
/**
* 获取StorageClient
* @param trackerServer
* @return
*/
public static StorageClient getStorageClient(TrackerServer trackerServer){
//通过TrackerServer的连接信息可以获取Storage的连接信息,创建StorageClient对象存储storage连接信息
StorageClient storageClient = new StorageClient(trackerServer, null);
return storageClient;
}
public static void main(String[] args) throws Exception {
//获取文件信息
// FileInfo file = getFileInfo("group1", "M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg");
// System.out.println("FileSize:"+file.getFileSize());
// System.out.println("IPAddr:"+file.getSourceIpAddr());
// //文件下载
// InputStream is = downloadFile("group1", "M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg");
// FileOutputStream os = new FileOutputStream("/Users/LiuShihao/Desktop/1.jpeg");
// //定义一个缓冲区
// byte[] buffer = new byte[1024];
// while(is.read(buffer)!=-1){
// os.write(buffer);
// }
// os.flush();
// os.close();
// is.close();
//文件删除
// deleteFile("group1", "M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg");
// 获取Tracker信息 IP+Port
// System.out.println(getTrackerInfo());
}
}
6.控制层
package com.mychanggou.controller;
import com.mychanggou.file.FastDFSFile;
import com.mychanggou.util.FastDFSUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* @author :LiuShihao
* @date :Created in 2020/9/17 8:51 下午
* @desc :
*/
@RestController
@RequestMapping("/file")
@CrossOrigin//跨域
public class FileUploadController {
@PostMapping("/upload")
public Result upload(@RequestParam("file")MultipartFile file) throws Exception {
if(file == null){
throw new RuntimeException("文件不存在");
}
//调用工具类 上传FastDFS文件服务器
//使用StringUtils.getFilenameExtension 可以获取文件扩展名
//获取文件名字、文件字节数组、文件扩展名 构造FastDFSFile对象
FastDFSFile fastDFSFile = new FastDFSFile(file.getOriginalFilename(),file.getBytes(),StringUtils.getFilenameExtension(file.getOriginalFilename()));
String[] upload = FastDFSUtil.upload(fastDFSFile);
//拼接访问地址
String url =FastDFSUtil.getTrackerInfo()+"/"+upload[0]+"/"+upload[1];
return new Result(true, StatusCode.OK,"上传成功",url);
}
}
三、上传测试
启动:
最后分享一下修改欢迎页的方法:
首先给个网址:
http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something%20
在中间那块区域输入你想要的文件,还可以选择字体等等,然后把形成的图像粘贴复制到一个txt中,取名banner.txt,然后把它放到resource目录下,之后启动项目就有了,每次要更换团就更换banner.txt中的内容即可。