Acceso SpringBoot FastDFS:
¿Qué es FastDFS?
FastDFS是用C语言编写的一款开源的轻量级分布式文件系统。它对文件进行管理,功能包括:文件存
储、文件同步、文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。特别适合
以文件为载体的在线服务,如相册网站、视频网站等等。
FastDFS为互联网量身定制,充分考虑了冗余备份、负载均衡、线性扩容等机制,并注重高可用、高性
能等指标,使用FastDFS很容易搭建一套高性能的文件服务器集群提供文件上传、下载等服务。
Funciones de FastDFS
Explicación detallada del sistema de gestión de archivos FastDFS
- Almacenamiento agrupado, estructura flexible, concisa y de igual a igual, sin archivos de un solo punto, sin almacenamiento en bloque, los archivos cargados se corresponden uno a uno con los archivos en el sistema de archivos del sistema operativo.
- FastDFS genera el ID del archivo como credencial de acceso a archivos. FastDFS no requiere un servidor de nombres tradicional y se conecta sin problemas con servidores web populares. FastDFS ha proporcionado módulos de extensión apache y nginx.
- Se pueden admitir archivos medianos y pequeños y admite el almacenamiento de archivos pequeños masivos.
- Admite múltiples discos y recuperación de datos de un solo disco
- Admite guardar solo una copia de archivos con el mismo contenido, ahorrando espacio en disco
- Admite expansión en línea y archivos maestro-esclavo
- Los atributos de archivo (metadatos) se pueden guardar en el servidor de almacenamiento. La comunicación de red V2.0 utiliza libevent, que admite un gran acceso simultáneo y tiene un mejor rendimiento general.
- La descarga de archivos admite subprocesos múltiples y reanuda la descarga en los puntos de interrupción.
Tutorial de instalación de fastDfsdocker
Código fuente completo de fastDfs
1.Introducir dependencias jar
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.6</version>
</dependency>
2.Configurar aplicación.yml
server:
port: 10086
# 分布式文件系统FDFS配置
fdfs:
connect-timeout: 600 # 连接超时时间
so-timeout: 1500 # 读取超时时间
tracker-list: 127.0.0.1:22122 # tracker服务配置地址列表,替换成自己服务的IP地址,支持多个
pool:
jmx-enabled: false
thumb-image:
height: 150 # 缩略图的宽高
width: 150
3. Cargar y descargar herramientas
@Component
public class FastdfsUtils {
public static final String DEFAULT_CHARSET = "UTF-8";
@Autowired
private FastFileStorageClient fastFileStorageClient;
/**
* 上传文件并返回文件路径
*
* @param file
* @return 文件路径
* @throws IOException
*/
public StorePath upload(MultipartFile file) throws IOException {
// 设置文件信息
Set<MetaData> mataData = new HashSet<>();
mataData.add(new MetaData("author", "fastdfs"));
mataData.add(new MetaData("description", file.getOriginalFilename()));
// 上传
StorePath storePath = fastFileStorageClient.uploadFile(
file.getInputStream(), file.getSize(),
FilenameUtils.getExtension(file.getOriginalFilename()),
null);
return storePath;
}
/**
* 根据全路径删除
*
* @param path "fullPath": "group1/M00/00/00/wKgAkGIfF2KAG7qSAAB-jaFjG-Q678.jpg"
*/
public void delete(String path) {
fastFileStorageClient.deleteFile(path);
}
/**
* 根据组和路径删除
* "group": "group1",
* "path": "M00/00/00/wKgAkGIfF2KAG7qSAAB-jaFjG-Q678.jpg",
* "fullPath": "group1/M00/00/00/wKgAkGIfF2KAG7qSAAB-jaFjG-Q678.jpg"
*
* @param group
* @param path
*/
public void delete(String group, String path) {
fastFileStorageClient.deleteFile(group, path);
}
/**
* 文件下载
*
* @param path 文件路径,例如:/group1/path=M00/00/00/itstyle.png
* @param filename 下载的文件命名
* @return
*/
public void download(String path, String filename, HttpServletResponse response) throws IOException {
// 获取文件
StorePath storePath = StorePath.parseFromUrl(path);
if (StringUtils.isBlank(filename)) {
filename = FilenameUtils.getName(storePath.getPath());
}
byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, DEFAULT_CHARSET));
response.setCharacterEncoding(DEFAULT_CHARSET);
// 设置强制下载不打开
// response.setContentType("application/force-download");
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.Clase de controlador
/**
* @author xlwang55
* @date 2022/3/2 13:47
*/
@RestController
@RequestMapping("/fastdfsUtils")
public class FastDFSUtilsController {
@Autowired
private FastdfsUtils fastdfsUtils;
@PostMapping("/upload")
public String upload(MultipartFile file) throws IOException {
StorePath storePath = fastdfsUtils.upload(file);
String fullPath = storePath.getFullPath();
System.out.println("fullPath = " + fullPath);
//group1/M00/00/00/wKgAkGIfF2KAG7qSAAB-jaFjG-Q678.jpg
return fullPath;
}
@GetMapping("/download")
public void downloadFile(String fileUrl, HttpServletResponse response)
throws IOException {
fastdfsUtils.download(fileUrl, null, response);
}
@DeleteMapping("/delete")
public void delete(String fileUrl) {
fastdfsUtils.delete(fileUrl);
}
}
5. Utilice el cartero para realizar pruebas.
5.1 Subir
http://localhost:10086/fastdfsUtils/upload
5.2 Descargar
http://localhost:10086/fastdfsUtils/download