当前位置:   article > 正文

池化资源-Commons Pool示例_apache commons pool 案例

apache commons pool 案例

       有开发经验的朋友应该都听过数据库连接池的概念,本节将简单的描述“池资源”。首先简单描述一下连接池中池化数据库连接资源的重要性:

  1. 频繁的创建和断开与数据库之间的连接是相当消耗性能的,增加了程序的内耗;
  2. 连接资源未释放或释放不合理导致数据库连接资源被长时间挂起进而影响数据库性能;
  3. 如果能在程序级别能控制访问数据库的各种策略是在好不过了,当然数据库本身也是允许的,对于多个应用程序而言如能够独立的维护自己的数据库资源是一种不错的选择。
  4. 其它,不可否认数据库连接池能给我们带来极大的方便,当然我们永远都记得任何东西自然有它不完美的存在。

      笔者层有一个幼稚的想法,假如我有若干资源(也许是数据库连接,JavaBean,自行车),我该如何使用上述“池化思想”来改善我对现有资源的不合理使用,第一想法当然是借鉴一下连接池的思想遇到如下问题:

  1. 池化的资源该如何保存 Array ?,Map?,List?
  2. 池化的资源什么该如何监管,谁拿走了?还剩余多少?谁该还回来了?
  3. 最重要的如何标记一个资源被借走了?又如何标记一个资源被还回来?

     此前没有此类的开发经验,理所当然的我认为自己需要重头开始写一个能满足上述需要的程序出来(为什么是程序不是框架,就因为水平太低,脑子里根本没有架构的概念),到此为止上述的问题都要一一解决,当然问题肯定层出不穷。我自然会放弃!开发者永远不要禁锢自己,退一步讲,有更适合现在这种情况的选择,你只需要多问,果不然我打听到了。现在目标很清楚有一个开源项目正好解决我的问题:commons-pool ,不得不说,小伙子!不懂就要问!肯定有人会!不会了再说!

     简单说一下,commons-pool 是一个开源项目,其目的就是为解决资源池化而生,对我而言完成任务是首要的,这也是还能写这篇文章的原因,学而不思则罔,今天简单回顾一下commons-poolhttp://commons.apache.org/proper/commons-pool/)的用法:

  1. 顶级接口PooledObjectFactory,用来创建池中的对象
    1. public interface PooledObjectFactory<T> {
    2. PooledObject<T> makeObject();//创建对象
    3. void activateObject(PooledObject<T> obj);//激活对象
    4. void passivateObject(PooledObject<T> obj);//钝化对象
    5. boolean validateObject(PooledObject<T> obj);//检查有效性
    6. void destroyObject(PooledObject<T> obj);//销毁对象
    7. }


  2. 顶级接口ObjectPool,代表一个池对象
  3. readerPool = new GenericObjectPool<MyReader>(new ReaderObjectFactory(tool), config);


       下将贴出一段开发中的案例供参考:

  1. PooledObjectFactory实现
    1. public class ReaderObjectFactory implements PoolableObjectFactory<MyReader> {
    2. private ArchiveTool tool;
    3. public ReaderObjectFactory(ArchiveTool tool) {
    4. this.setTool(tool);
    5. }
    6. public MyReader makeObject() throws Exception {
    7. MyReader reader = new MyReader();
    8. try {
    9. ArchiveReader ar = tool.createArchiveReader();
    10. reader.setIsValid(true);
    11. reader.setReader(ar);
    12. } catch (Exception e) {
    13. e.printStackTrace();
    14. }
    15. return reader;
    16. }
    17. public void destroyObject(MyReader obj) throws Exception {
    18. try {
    19. obj.getReader().release();
    20. } catch (Exception e) {
    21. e.printStackTrace();
    22. }
    23. }
    24. public boolean validateObject(MyReader obj) {
    25. try {
    26. return obj.getIsValid();
    27. } catch (Exception e) {
    28. e.printStackTrace();
    29. }
    30. return false;
    31. }
    32. public void activateObject(MyReader obj) throws Exception {
    33. }
    34. public void passivateObject(MyReader obj) throws Exception {
    35. }
    36. public ArchiveTool getTool() {
    37. return tool;
    38. }
    39. public void setTool(ArchiveTool tool) {
    40. this.tool = tool;
    41. }
    42. }


  2. 资源使用案例

    1. public class DHDFSFileManager {
    2. private static Logger Log = Logger.getLogger(DHDFSFileManager.class);
    3. private static EFSConfig cfg;
    4. private static ArchiveTool tool;
    5. //对象池
    6. private static ObjectPool<MyReader> readerPool;
    7. //线程绑定
    8. private static ThreadLocal<LRUAri<ArchiveWriter>> thread = new ThreadLocal<LRUAri<ArchiveWriter>>();
    9. public static void main(String[] args) throws IOException {
    10. if (DHDFSFileManager.init("172.16.248.160", 38100, "root", "123456")) {
    11. InputStream in = DHDFSFileManager.class.getResourceAsStream("car.jpg");
    12. String bucket = genBucket(new Date());
    13. FileOutputStream o = new FileOutputStream("/test/T1/load.jpg");
    14. byte[] buf = IOUtils.toByteArray(in);
    15. o.write(buf);
    16. o.close();
    17. String fileName = DHDFSFileManager.uploadFile(buf, bucket);
    18. System.out.println("fileName:" + fileName);
    19. byte[] context = DHDFSFileManager
    20. .downloadFile("2016-11-25/archivefile-2016-11-25-131859-00C948B800000001:64/448092.jpg");
    21. FileOutputStream out = new FileOutputStream(new File("./load.jpg"));
    22. out.write(context);
    23. out.close();
    24. System.out.println(context.length);
    25. }
    26. }
    27. /**
    28. * <h1>初始化ArchiveTool,在使用之前须先调用初始化方法
    29. *
    30. * @param address
    31. * DFS host name or IP address
    32. * @param port
    33. * host port
    34. * @param userName
    35. * user name
    36. * @param password
    37. * user pass
    38. *
    39. * @return success ?true : false
    40. */
    41. public static boolean init(String address, int port, String userName, String password) {
    42. if (tool == null) {
    43. synchronized (DHDFSFileManager.class) {
    44. if (tool == null) {
    45. cfg = new EFSConfig.ByReference();
    46. cfg.address = address;
    47. cfg.port = port;
    48. cfg.userName = userName;
    49. cfg.password = password;
    50. tool = new ArchiveTool();
    51. if (!tool.init(cfg)) {
    52. Log.error(cfg.address + "_" + cfg.port + "_" + cfg.userName + "_" + cfg.password);
    53. Log.error("init ArchiveTool fail!!");
    54. System.out.println("init ArchiveTool fail!!");
    55. return false;
    56. }
    57. Log.info("init ArchiveTool success");
    58. if (!tool.efsSetLog("./logs/", EFSLogLevel.INFOF)) {
    59. Log.error("init SystemLog fail!!");
    60. System.out.println("init SystemLog fail!!");
    61. return false;
    62. }
    63. Log.info("init SystemLog success");
    64. // 初始化Bucket
    65. String bucket = genBucket(new Date());
    66. if (!tool.isBucketValid(bucket)) {
    67. if (!tool.createBucket(bucket)) {
    68. System.out.println("create bucket:" + bucket + " fail!!");
    69. return false;
    70. }
    71. }
    72. Log.info("init Bucket success");
    73. // 初始化对象池
    74. Config config = new Config();
    75. config.maxActive = 1;
    76. config.minIdle = 1;
    77. readerPool = new GenericObjectPool<MyReader>(new ReaderObjectFactory(tool), config);
    78. //初始化绑定到线程的变量
    79. thread.set(new LRUAri<ArchiveWriter>(5));
    80. Log.info("init Writer Pool success");
    81. System.out.println("init succeess and END");
    82. return true;
    83. }
    84. }
    85. } else {
    86. System.out.println("arready init!!");
    87. return false;
    88. }
    89. return false;
    90. }
    91. /**
    92. * <h1>上传文件
    93. *
    94. * @param img
    95. * image byte array
    96. * @param bucket
    97. * bucket name
    98. * @return filename
    99. */
    100. public static String uploadFile(byte[] img, String bucket) {
    101. long start = System.currentTimeMillis();
    102. System.out.println("sdtart upload,time:" + start);
    103. ArchiveWriter aw = null;
    104. String archname = null;
    105. try {
    106. checkOrCreateBucket(bucket);
    107. // aw.setBucket(bucket);
    108. aw = getWriter(bucket);
    109. aw.open("jpg");
    110. int len = img.length;
    111. System.out.println("length:" + len);
    112. int writeData = 0;
    113. int offset = 0;
    114. while (writeData < len) {
    115. int ret = aw.write(img, len - offset);
    116. if (ret < 0) {
    117. System.out.println("write faile");
    118. throw new Exception("write faile");
    119. }
    120. System.out.println(ret);
    121. writeData += ret;
    122. offset += ret;
    123. }
    124. System.out.println("writeSize:" + writeData);
    125. archname = aw.close();
    126. Log.debug("upload{time:" + new Date().toString() + ",fileName:" + archname + "}");
    127. System.out.println("end upload,time:" + System.currentTimeMillis());
    128. System.out.println("interval time:" + (System.currentTimeMillis() - start));
    129. Log.info("文件上传成功,FileName:" + archname);
    130. // writer.setIsValid(false);
    131. } catch (Exception e) {
    132. e.printStackTrace();
    133. Log.error("文件上传失败!!");
    134. return archname;
    135. } finally {
    136. aw = null;
    137. }
    138. return archname;
    139. }
    140. /**
    141. * <h1>下载文件
    142. *
    143. * @param archname
    144. * fileName
    145. * @return byte array image content
    146. */
    147. public static byte[] downloadFile(String archname) {
    148. long start = System.currentTimeMillis();
    149. System.out.println("start download,time:" + start);
    150. MyReader reader = null;
    151. ArchiveReader ar = null;
    152. ByteArrayOutputStream out = null;
    153. try {
    154. reader = readerPool.borrowObject();
    155. ar = reader.getReader();
    156. ArchiveInfo ai = tool.getArchiveInfos(archname);
    157. String fileName = ai.getFilename();
    158. int len = (int) ar.open(fileName);
    159. System.out.println("fileLen:" + len);
    160. out = new ByteArrayOutputStream();
    161. byte[] buf = new byte[len];
    162. int getData = 0;
    163. while (getData < len) {
    164. int ret = ar.read(buf, len);
    165. if (ret > 0) {
    166. getData += ret;
    167. out.write(buf, 0, ret);
    168. }
    169. if (ret == -1) {
    170. System.out.println("read faile");
    171. break;
    172. }
    173. }
    174. Log.debug("upload{time:" + new Date().toString() + ",fileName:" + archname + "}");
    175. ar.close();
    176. Log.info("文件下载成功,FileName:" + archname);
    177. System.out.println("end download,time:" + System.currentTimeMillis());
    178. System.out.println("interval time :" + (System.currentTimeMillis()-start));
    179. Log.debug("interval time :" + (start - System.currentTimeMillis()));
    180. return out.toByteArray();
    181. } catch (Exception e) {
    182. // 失败
    183. reader.setIsValid(false);
    184. e.printStackTrace();
    185. Log.debug("downloadfail{time:" + new Date().toString() + ",interval time :"
    186. + (start - System.currentTimeMillis()) + ",fileName:" + archname + "}");
    187. System.out.println("文件下载失败!!");
    188. return null;
    189. } finally {
    190. try {
    191. if (out != null) {
    192. out.close();
    193. }
    194. } catch (Exception e) {
    195. e.printStackTrace();
    196. }
    197. try {
    198. //释放资源
    199. readerPool.returnObject(reader);
    200. } catch (Exception e) {
    201. e.printStackTrace();
    202. }
    203. }
    204. }
    205. /**
    206. * <h1>get a bucket
    207. *
    208. * @param date
    209. * time
    210. * @return bucket name format by "yyyy-MM-dd"
    211. */
    212. public static String genBucket(Date date) {
    213. String pattren = "yyyy-MM-dd";
    214. return new SimpleDateFormat(pattren).format(date);
    215. }
    216. /**
    217. * <h1>get a bucket
    218. *
    219. * @param date
    220. * time
    221. * @return bucket name format by "yyyy-MM-dd"
    222. */
    223. public static String genBucket(String date) {
    224. String pattren = "yyyy-MM-dd";
    225. return date.substring(0, pattren.length());
    226. }
    227. /**
    228. * <h1>get a bucket
    229. *
    230. * @param bucket
    231. * bucket name
    232. * @return delete success ?true:false
    233. */
    234. public static boolean deleteBucket(String bucket) {
    235. try {
    236. if (!tool.isBucketValid(bucket)) {
    237. Log.error("bucket:" + bucket + " not exist");
    238. return true;
    239. } else {
    240. if (tool.removeBucket(bucket)) {
    241. Log.info("delete bucket:" + bucket);
    242. return true;
    243. } else {
    244. Log.error("delete bucket :" + bucket + " error!!");
    245. return false;
    246. }
    247. }
    248. } catch (Exception e) {
    249. e.printStackTrace();
    250. }
    251. return false;
    252. }
    253. public static Object obj = "";
    254. public static void checkOrCreateBucket(String bucket) {
    255. try {
    256. if (!tool.isBucketValid(bucket)) {
    257. synchronized (obj) {
    258. if (!tool.isBucketValid(bucket)) {
    259. tool.createBucket(bucket);
    260. }
    261. }
    262. }
    263. } catch (Exception e) {
    264. e.printStackTrace();
    265. }
    266. }
    267. public static Object obj1 = "";
    268. /**
    269. * <h1>get ArchiveWriter from Thread Local
    270. *
    271. * @param bucket
    272. * bucket name
    273. * @return ArchiveWriter write file
    274. */
    275. public static ArchiveWriter getWriter(String bucket) {
    276. LRUAri<ArchiveWriter> writers = thread.get();
    277. Log.debug(writers);
    278. if (writers == null) {
    279. writers = new LRUAri<ArchiveWriter>(5);
    280. thread.set(writers);
    281. }
    282. ArchiveWriter writer = writers.get(bucket);
    283. if (writer == null) {
    284. synchronized (obj1) {
    285. if (writers.get(bucket) == null) {
    286. writer = tool.createArchiveWriter();
    287. writer.init((byte) 3, (byte) 1, bucket);
    288. writers.put(bucket, writer);
    289. thread.set(writers);
    290. }
    291. }
    292. }
    293. return writer;
    294. }
    295. }





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/617956
推荐阅读
相关标签
  

闽ICP备14008679号