FastDFS多线程问题

来源:互联网 发布:js隐藏鼠标指针 编辑:程序博客网 时间:2024/04/28 00:29

    在项目中用到FastDFS,用来存图片,刚开始单线程进行测试,所以没什么问题,但是在多个客户端进行上传后,发现经常性的会报一下错误:


FastDFS多线程经常性会遇到这样的问题,线程测试的代码如下:

(1)多线程下载代码

public class FastdfsClientTest {

public static void main(String[] args) {
final String fileName = "d:\\download1";
 for (int i = 0; i < 20; i++) {
           new Thread(new Runnable() {
            public void run() {
            for (int j = 0; j < 6; j++) {
try {
String group_name = "group2";
String remote_filename = "/M00/00/04/O03saVlz_fmAWxyEAAMbzl2LTmk854.tif";
FastdfsClient.download1(group_name,remote_filename,fileName+Thread.currentThread().getId()+j+".tif");
} catch (Exception e) {
e.printStackTrace();
}
            //System.out.println(Thread.currentThread().getName());
}
               }
           }).start();
       }

}
}

(2)多线程上传代码

public static void uploadFile(){
String[] strings = null;
StorageClient storageClient = null;
try {
String configFilePath = "fdfs_client.conf";
System.out.println("Configuration file:" + configFilePath);
ClientGlobal.init(configFilePath);
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
storageClient = new StorageClient(trackerServer, storageServer);
} catch (Exception e) {
e.printStackTrace();
}
try {
strings = storageClient.upload_file("D:\\图片\\1.tif", "tif", null);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
System.out.println(strings[0]+"/"+ strings[1]);
}

public static void main(String[] args) {
 //多线程插入测试
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);  
 for (int i = 0; i < 10; i++) {  
  final int index = i;  
  fixedThreadPool.execute(new Runnable() {  
   public void run() {  
    MutiInsert.uploadFile();
       System.out.println(index);  
   }  
  });  
 } 
}

         这主要是因为FastDFS本身的客户端并不支持多个客户端,所以在网上下载了一个FastDFS的连接池,但是一般的连接池只是提供上传和删除的方法,并不会提供查询的方法,经过查阅发现FastDFS的图片下载是通过Nginx方式进行的,不是直接通过Java客户端的方式

通过以上的方式就能实现多线程上传、删除和查询。