简单 fastdfs java client 连接池

package com.xyh.core.fastdfs;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.DownloadCallback;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.csource.fastdfs.UploadCallback;
import org.springframework.http.HttpHeaders;

public class FastDfsPool {
	//默认连接池大小
	public static int connection_size = 20;
	private static TrackerClient trackerClient;
	private static LinkedBlockingQueue storageClient1s = new LinkedBlockingQueue(
			connection_size);
	private static int current_index;

	static {
		try {
			String classPath = new File(FileManager.class.getResource("/").getFile()).getCanonicalPath();
			String fdfsClientConfigFilePath = classPath + File.separator + FileManagerConfig.CLIENT_CONFIG_FILE;
			ClientGlobal.init(fdfsClientConfigFilePath);
			trackerClient = new TrackerClient();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private FastDfsPool() {

	}

	public static String getFileExt(String local_filename) {
		int nPos = local_filename.lastIndexOf('.');
		if (nPos > 0 && local_filename.length() - nPos <= ProtoCommon.FDFS_FILE_EXT_NAME_MAX_LEN + 1) {
			return local_filename.substring(nPos + 1);
		}
		return "";
	}

	private static void createStorageClientInfo() {
		synchronized (trackerClient) {
			if (current_index < connection_size) {
				try {
					System.out.println("创建连接");
					TrackerServer server = trackerClient.getConnection();
					StorageClient1 storageClient1 = new StorageClient1(trackerClient.getConnection(), null);
					StorageClientInfo storageClientInfo = new StorageClientInfo(current_index, storageClient1, server);
//					System.out.println(storageClientInfo.id+"====================");
					if (storageClient1s.offer(storageClientInfo)) {
						current_index++;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static StorageClientInfo findStorageClient() {
		// 尝试获取一个有用的客户端连接信息
		StorageClientInfo clientInfo = storageClient1s.poll();
		if (clientInfo == null) {
//			System.out.println("没有找到可用的空闲连接");
			if (current_index < connection_size) {
				createStorageClientInfo();
			}else{
//				System.out.println("等待连接可用");
			}
			try {
				clientInfo=storageClient1s.poll(10,TimeUnit.SECONDS);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return clientInfo;
	}

	public static void downloadFile(String path, HttpServletRequest request, HttpServletResponse response) {
		StorageClientInfo client1 = findStorageClient();
		if(client1!=null){
			try {
				String type = request.getServletContext().getMimeType(path);
				if (type != null) {
					response.setContentType(type);
				}
				if (path.startsWith("/")) {
					path = path.substring(1);
				}
				FileDownLoad fileDownLoad = new FileDownLoad(response);
//				System.out.println("down load file "+path+" from "+client1.id+" server");
				client1.storageClient1.download_file1(path, fileDownLoad);
				if (fileDownLoad.out == null) {
					response.setStatus(404);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (MyException e) {
				e.printStackTrace();
			}finally {
				storageClient1s.offer(client1);
			}
		}else{
			try {
				response.sendError(500, "fastdfs file down server error");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @param in
	 *            文件输入流
	 * @param valuePairs
	 *            元信息
	 * @param local_filename
	 *            文件名
	 * @param size
	 *            文件大小
	 * @return 上传后的文件路径
	 * @throws MyException
	 * @throws IOException
	 */

	public static String upload(String local_filename, long size, InputStream in, NameValuePair[] valuePairs){

		StorageClientInfo client1 = findStorageClient();
		if(client1!=null){
			
			String file_ext_name = null;
			if (file_ext_name == null) {
				int nPos = local_filename.lastIndexOf('.');
				if (nPos > 0 && local_filename.length() - nPos <= ProtoCommon.FDFS_FILE_EXT_NAME_MAX_LEN + 1) {
					file_ext_name = local_filename.substring(nPos + 1);
				}
			}
			
			String path=null;
			try {
				path=client1.storageClient1.upload_file1(null, size, new FileUpload(in), file_ext_name, valuePairs);
			} catch (Exception e1) {
				e1.printStackTrace();
			}finally {
				try {
					if(client1.trackerServer.getSocket().isConnected()){
						storageClient1s.offer(client1);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return path;
		}
		return null;
		
		

	}

	private static class StorageClientInfo {
		public int id;
		public StorageClient1 storageClient1;
		public TrackerServer trackerServer;

		public StorageClientInfo(int id, StorageClient1 storageClient1, TrackerServer trackerServer) {
			this.storageClient1 = storageClient1;
			this.trackerServer = trackerServer;
			this.id=id;
		}

	}

	private static class FileUpload implements UploadCallback {
		private InputStream in;

		public FileUpload(InputStream in) {
			this.in = in;
		}

		public int send(OutputStream out) throws IOException {
			try {
				BufferedOutputStream bufferOut = new BufferedOutputStream(out);
				if (in instanceof FileInputStream) {
					in = new BufferedInputStream(in);
				}
				byte[] buff = new byte[4096];
				int off = -1;
				while ((off = in.read(buff)) != -1) {
					bufferOut.write(buff, 0, off);
				}
				bufferOut.flush();
			} catch (Exception e) {
				throw e;
			} finally {
				in.close();
			}
			return 0;
		}
	}

	private static class FileDownLoad implements DownloadCallback {
		private HttpServletResponse response;
		private OutputStream out;

		public FileDownLoad(HttpServletResponse response) {
			this.response = response;
		}

		@Override
		public int recv(long file_size, byte[] data, int bytes) {
			if (out == null) {
				response.setContentLengthLong(file_size);
				response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=864000");
				response.setHeader("Pragma", "Pragma");
				response.setDateHeader("Last-Modified", System.currentTimeMillis());
				try {
					out = response.getOutputStream();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.write(data, 0, bytes);
				} catch (IOException e) {
					e.printStackTrace();
					return -1;
				}
			} else {
				return -1;
			}
			return 0;
		}

	}

	public static void deleteFile(String groupName, String remoteFileName) {
		StorageClientInfo client = findStorageClient();
		try {
			client.storageClient1.delete_file(groupName, remoteFileName);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MyException e) {
			e.printStackTrace();
		}finally{
			storageClient1s.offer(client);
		}
	}

}

 

转载于:https://my.oschina.net/microxdd/blog/890247

你可能感兴趣的:(简单 fastdfs java client 连接池)