123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- package cn.stylefeng.guns.zjxlUtil;
- import org.csource.fastdfs.ClientGlobal;
- import org.csource.fastdfs.StorageClient;
- import org.csource.fastdfs.TrackerClient;
- import org.csource.fastdfs.TrackerServer;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Map.Entry;
- /**
- * Created by szx on 2015/9/19.
- */
- public class FastDFSClientPool {
- private static volatile FastDFSClientPool pool;
- private Map<StorageClient, Boolean> map;
- private int maxPoolSize = 20;
- private int waitTime = 500;
- private int initPoolSize = 5;
- static {
- try {
-
- String basePath = FastDFSClientPool.class.getResource("/").getPath();
-
- ClientGlobal.init(FastDFSUtil.class.getResource("/config/fdfs_client.conf").getPath());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private FastDFSClientPool() {
- init();
- }
- public static FastDFSClientPool getInstance() {
- if (pool == null) {
- synchronized (FastDFSClientPool.class) {
- if(pool == null) {
- pool = new FastDFSClientPool();
- }
- }
- }
- System.out.println("FastDFSClientPool:"+pool.toString());
- return pool;
- }
- private void init() {
- try {
- map = new HashMap<StorageClient, Boolean>();
- //不做初始缓存
- // for (int i = 0; i < initPoolSize; i++) {
- // map.put(getNewStorageClient(), true);
- // }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public TrackerServer getTrackerServer(){
- try {
- TrackerClient tracker = new TrackerClient();
- return tracker.getConnection();
- }catch (Exception e){
- e.printStackTrace();
- }
- return null;
- }
- private StorageClient getNewStorageClient() {
- try {
- TrackerClient tracker = new TrackerClient();
- TrackerServer trackerServer = tracker.getConnection();
- StorageClient client = new StorageClient(trackerServer, null);
- return client;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- public synchronized StorageClient getStorageClient() {
- StorageClient client = null;
- try {
- for (Entry<StorageClient, Boolean> entry : map.entrySet()) {
- if (entry.getValue()) {
- client = entry.getKey();
- System.out.println("从缓存中获得fastdfs client");
- map.put(client, false);
- break;
- }
- }
- if (client == null) {
- if(map.size()<maxPoolSize) {
- System.out.println("创建新fastdfs client:");
- client = getNewStorageClient();
- map.put(client, false);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return client;
- }
- public void releaseStorageClient(StorageClient client) {
- if (client == null) {
- return;
- }
- try {
- if(map.containsKey(client)) {
- map.put(client, true);
- } else {
- client =null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
|