FastDFSClientPool.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.yihu.base.fastdfs;
  2. import org.csource.fastdfs.StorageClient;
  3. import org.csource.fastdfs.TrackerClient;
  4. import org.csource.fastdfs.TrackerServer;
  5. import java.io.IOException;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. /**
  10. * Created by szx on 2015/9/19.
  11. */
  12. public class FastDFSClientPool {
  13. private int maxPoolSize;
  14. private Map<StorageClient, Boolean> map = new HashMap<>();
  15. public void setMaxPoolSize(int poolSize){
  16. this.maxPoolSize = poolSize;
  17. }
  18. public TrackerServer getTrackerServer() throws IOException {
  19. TrackerClient tracker = new TrackerClient();
  20. return tracker.getConnection();
  21. }
  22. private StorageClient getNewStorageClient() throws IOException {
  23. TrackerClient tracker = new TrackerClient();
  24. TrackerServer trackerServer = tracker.getConnection();
  25. StorageClient client = new StorageClient(trackerServer, null);
  26. return client;
  27. }
  28. public synchronized StorageClient getStorageClient() throws IOException {
  29. StorageClient client = null;
  30. for (Entry<StorageClient, Boolean> entry : map.entrySet()) {
  31. if (entry.getValue()) {
  32. client = entry.getKey();
  33. map.put(client, false);
  34. break;
  35. }
  36. }
  37. if (client == null) {
  38. if (map.size() < maxPoolSize) {
  39. client = getNewStorageClient();
  40. map.put(client, false);
  41. }
  42. }
  43. return client;
  44. }
  45. public void releaseStorageClient(StorageClient client) {
  46. if (client == null) return;
  47. if (map.containsKey(client)) {
  48. map.put(client, true);
  49. } else {
  50. client = null;
  51. }
  52. }
  53. }