02 fastdfs-client访问fastdfs服务
本文将阐述使用fastdfs客户端插件去访问fastdfs服务。
1、环境约束
- idea2018.1.5
- jdk-8u162-windows-x64
2、前提约束
- 已经安装fastdfs服务,作者的图片服务器ip为 192.168.100.192,请读者根据自己的实际情况修改ip,storaged端口一般为22122
2、源代码下载
官网:
https://github.com/happyfish100/fastdfs-client-java
百度网盘:
链接:https://pan.baidu.com/s/1CeQ6CWg7tlJy9MalF8NCeg
提取码:ptco
3、解压,使用idea打开该项目
以下为项目结构:
4、修改fdfs_client.conf
源码中已经有配置,我们简化处理,修改fdfs_client.conf为以下内容:
tracker_server=192.168.100.192:22122
5、测试文件上传【确保在src同级目录下有一个1.png图片】
在src/java中新建TestUpload.java
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException, MyException {
//1、加载配置文件
ClientGlobal.init("fdfs_client.conf");
//2、创建一个TrackerClient对象。
TrackerClient trackerClient = new TrackerClient();
//3、使用TrackerClient对象获得trackerserver对象。
TrackerServer trackerServer = trackerClient.getConnection();
//4、创建一个StorageClient对象。trackerserver、StorageServer两个参数。
StorageClient storageClient = new StorageClient(trackerServer, null);
//5、使用StorageClient对象上传文件。
String[] strings = storageClient.upload_file("1.png", "png", null);
//返回的数组包含两个元素分别类似于:group1、M00/00/00/wKhkwFyuYo6Aawy0AAH4I7umxyo333.png
for (String string : strings) {
System.out.println(string);
}
}
}
6、测试文件下载【记录上面上传文件返回的两个值,即group,M00/】
在src/java中创建TestDownload.java
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import java.io.IOException;
public class TestDownload {
public static void main(String[] args) throws IOException, MyException {
//1、加载配置文件
ClientGlobal.init("fdfs_client.conf");
//2、创建一个TrackerClient对象。
TrackerClient trackerClient = new TrackerClient();
//3、使用TrackerClient对象获得trackerserver对象。
TrackerServer trackerServer = trackerClient.getConnection();
//4、创建一个StorageClient对象。trackerserver、StorageServer两个参数。
StorageClient storageClient = new StorageClient(trackerServer, null);
//5、使用StorageClient对象下载文件。
storageClient.download_file("group1", "M00/00/00/wKhkwFyuZo-AHPJEAAH4I7umxyo675.png", "2.png");
}
}
至此,我们使用fastdfs-client完成了文件的上传和下载。不过要注意的是,在实际使用过程中,我们自己的项目用的是该开源项目生成的jar包,并非直接使用该源代码。