• 对象池commons-pool2


    1.序言

    对象池就是存访对象的池,跟线程池,数据库连接池等一样,典型的池化设计思想

    对象池的优点:

    1.集中管理池中对象,

    2.减少频繁创建和销毁长期使用的对象,提升复用性,以节约资源的消耗

    3.可以有效避免频繁为对象分配内存和释放堆中内存,减轻jvm垃圾收集器的负担

    common-pocol2 是Apache提供的一个通用对象池技术实现,可以方便定制化自己需要的对象池。

    先说怎么用?

    这里以fastdfs举例,fastdfs对象是典型线程不安全,底层是socket连接,每使用一次就new一个socket对象,完成后关闭对象。

    2.pom.xml引入

    1. <dependency>
    2. <groupId>org.apache.commons</groupId>
    3. <artifactId>commons-pool2</artifactId>
    4. <version>2.11.1</version>
    5. </dependency>

    3.构建要池化的对象,对象池,对象工厂

    需要池化的对象FastdfsClient

    1. import org.csource.fastdfs.StorageClient1;
    2. import org.csource.fastdfs.StorageServer;
    3. import org.csource.fastdfs.TrackerServer;
    4. /**
    5. * 封装自建的fastdfs对象
    6. */
    7. public class FastdfsClient extends StorageClient1 {
    8. private String name;
    9. private boolean active;
    10. public FastdfsClient(){
    11. super();
    12. }
    13. public FastdfsClient(TrackerServer trackerServer, StorageServer storageServer){
    14. super(trackerServer, storageServer);
    15. }
    16. public String getName() {
    17. return name;
    18. }
    19. public void setName(String name) {
    20. this.name = name;
    21. }
    22. public boolean isActive() {
    23. return active;
    24. }
    25. public void setActive(boolean active) {
    26. this.active = active;
    27. }
    28. public void destroy(){
    29. this.active = false;
    30. }
    31. public void active(){
    32. this.active = true;
    33. }
    34. }

    对象池FastDFSClientPool

    1. import org.apache.commons.pool2.PooledObjectFactory;
    2. import org.apache.commons.pool2.impl.AbandonedConfig;
    3. import org.apache.commons.pool2.impl.GenericObjectPool;
    4. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    5. public class FastDFSClientPool extends GenericObjectPool<FastdfsClient> {
    6. public FastDFSClientPool(PooledObjectFactory<FastdfsClient> factory) {
    7. super(factory);
    8. }
    9. public FastDFSClientPool(PooledObjectFactory<FastdfsClient> factory, GenericObjectPoolConfig<FastdfsClient> config) {
    10. super(factory, config);
    11. }
    12. public FastDFSClientPool(PooledObjectFactory<FastdfsClient> factory, GenericObjectPoolConfig<FastdfsClient> config, AbandonedConfig abandonedConfig) {
    13. super(factory, config, abandonedConfig);
    14. }
    15. }

    对象工厂FastdfsClientFactory,用来激活,销毁,构建,钝化,校验对象的地方

    1. import com.achi.common.model.ExceptionCode;
    2. import com.achi.common.service.ConfigService;
    3. import com.achi.core.exception.ServiceException;
    4. import com.achi.core.utils.RandomGUID;
    5. import org.apache.commons.pool2.PooledObject;
    6. import org.apache.commons.pool2.PooledObjectFactory;
    7. import org.apache.commons.pool2.impl.DefaultPooledObject;
    8. import org.apache.log4j.Logger;
    9. import org.csource.common.MyException;
    10. import org.csource.fastdfs.*;
    11. import org.springframework.beans.factory.annotation.Autowired;
    12. import org.springframework.stereotype.Component;
    13. import java.io.IOException;
    14. import java.net.InetSocketAddress;
    15. import java.util.ArrayList;
    16. import java.util.List;
    17. import java.util.Map;
    18. @Component
    19. public class FastdfsClientFactory implements PooledObjectFactory<FastdfsClient> {
    20. protected final static Logger log = Logger.getLogger(FastdfsClientFactory.class);
    21. public List<String> uriList = new ArrayList<>();
    22. public static final String PRE = "fastdfs.client_";
    23. @Autowired
    24. private ConfigService configService;
    25. /**
    26. * 激活对象,使其可用
    27. * @param pooledObject
    28. * @throws Exception
    29. */
    30. @Override
    31. public void activateObject(PooledObject<FastdfsClient> pooledObject) throws Exception {
    32. FastdfsClient fastDFSClient = pooledObject.getObject();
    33. // log.info(fastDFSClient.getName() + ",激活对象,使其可用");
    34. fastDFSClient.active();
    35. }
    36. /**
    37. * 销毁对象
    38. * @param pooledObject
    39. * @throws Exception
    40. */
    41. @Override
    42. public void destroyObject(PooledObject<FastdfsClient> pooledObject) throws Exception {
    43. FastdfsClient fastDFSClient = pooledObject.getObject();
    44. log.info(fastDFSClient.getName() + ",销毁对象");
    45. fastDFSClient.destroy();
    46. }
    47. /**
    48. * 构建对象
    49. * @return
    50. * @throws Exception
    51. */
    52. @Override
    53. public PooledObject<FastdfsClient> makeObject() throws Exception {
    54. FastdfsClient fastDFSClient = getFastdfsClient();
    55. if(fastDFSClient == null){
    56. throw new ServiceException(ExceptionCode.MESSAGE, "create FastdfsClient error.");
    57. }
    58. log.info(fastDFSClient.getName() + ",销毁对象");
    59. return new DefaultPooledObject<>(fastDFSClient);
    60. }
    61. /**
    62. * 钝化对象,反初始化 此"对象"暂且需要"休息"一下
    63. * @param pooledObject
    64. * @throws Exception
    65. */
    66. @Override
    67. public void passivateObject(PooledObject<FastdfsClient> pooledObject) throws Exception {
    68. // log.info(pooledObject.getObject().getName() + ",钝化一个对象");
    69. }
    70. /**
    71. * 验证对象是否可用
    72. * @param pooledObject
    73. * @return
    74. */
    75. @Override
    76. public boolean validateObject(PooledObject<FastdfsClient> pooledObject) {
    77. FastdfsClient fastDFSClient = pooledObject.getObject();
    78. return fastDFSClient.isActive();
    79. }
    80. private void init() throws ServiceException {
    81. Map<String, Object> configMap = configService.getRootConfig();
    82. if (configMap == null) {
    83. return;
    84. }
    85. Map<String, Object> fdfsMap = (Map<String, Object>)configMap.get("fdfs");
    86. if (fdfsMap == null) {
    87. return;
    88. }
    89. uriList = (List<String>)fdfsMap.get("uri");
    90. if (uriList == null) {
    91. throw new ServiceException(ExceptionCode.NULL_PARAMETER, "No uri of fdfs in Config.");
    92. }
    93. }
    94. private FastdfsClient getFastdfsClient() throws ServiceException{
    95. FastdfsClient fastdfsClient = null;
    96. try {
    97. if(uriList == null || uriList.isEmpty()){
    98. init();
    99. }
    100. ClientGlobal.init(getClass().getResource("/fdfs_client.conf").getPath());
    101. InetSocketAddress[] trackerServers = new InetSocketAddress[uriList.size()];
    102. for (int i = 0; i < uriList.size(); i++) {
    103. String[] address = uriList.get(i).split(":");
    104. trackerServers[i] = new InetSocketAddress(address[0].trim(), Integer.parseInt(address[1].trim()));
    105. }
    106. ClientGlobal.setG_tracker_group(new TrackerGroup(trackerServers));
    107. TrackerClient trackerClient = new TrackerClient();
    108. TrackerServer trackerServer = trackerClient.getConnection();
    109. if (trackerServer == null) {
    110. return null;
    111. }
    112. ProtoCommon.activeTest(trackerServer.getSocket());
    113. StorageServer storageServer = null;
    114. fastdfsClient = new FastdfsClient(trackerServer, storageServer);
    115. fastdfsClient.setName(PRE + new RandomGUID());
    116. fastdfsClient.active();
    117. } catch (IOException | MyException e) {
    118. log.error(e.getMessage(), e);
    119. }
    120. return fastdfsClient;
    121. }
    122. }

    4.与spring集成,构建对象池bean

    1. import com.achi.config.fastdfs.FastDFSClientPool;
    2. import com.achi.config.fastdfs.FastdfsClient;
    3. import com.achi.config.fastdfs.FastdfsClientFactory;
    4. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.context.annotation.Bean;
    7. import org.springframework.context.annotation.Configuration;
    8. import javax.annotation.PreDestroy;
    9. import java.util.concurrent.TimeUnit;
    10. @Configuration
    11. public class FastdfsPoolConfiguration {
    12. private FastDFSClientPool fastDFSClientPool;
    13. @Autowired
    14. private FastdfsClientFactory fastdfsClientFactory;
    15. /**
    16. * maxActive: 链接池中最大连接数,默认为8.
    17. * maxIdle: 链接池中最大空闲的连接数,默认为8.
    18. * minIdle: 连接池中最少空闲的连接数,默认为0.
    19. * maxWait: 当连接池资源耗尽时,调用者最大阻塞的时间,超时将跑出异常。单位,毫秒数;默认为-1.表示永不超时.
    20. * minEvictableIdleTimeMillis: 连接空闲的最小时间,达到此值后空闲连接将可能会被移除。负值(-1)表示不移除。
    21. * softMinEvictableIdleTimeMillis: 连接空闲的最小时间,达到此值后空闲链接将会被移除,且保留“minIdle”个空闲连接数。默认为-1.
    22. * numTestsPerEvictionRun: 对于“空闲链接”检测线程而言,每次检测的链接资源的个数。默认为3.
    23. * testOnBorrow: 向调用者输出“链接”资源时,是否检测是有有效,如果无效则从连接池中移除,并尝试获取继续获取。默认为false。建议保持默认值.
    24. * testOnReturn: 向连接池“归还”链接时,是否检测“链接”对象的有效性。默认为false。建议保持默认值.
    25. * testWhileIdle: 向调用者输出“链接”对象时,是否检测它的空闲超时;默认为false。如果“链接”空闲超时,将会被移除。建议保持默认值.
    26. * timeBetweenEvictionRunsMillis: “空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1.
    27. * whenExhaustedAction: 当“连接池”中active数量达到阀值时,即“链接”资源耗尽时,连接池需要采取的手段, 默认为1:
    28. * -> 0 : 抛出异常,
    29. * -> 1 : 阻塞,直到有可用链接资源
    30. * -> 2 : 强制创建新的链接资源
    31. * @return
    32. */
    33. @Bean
    34. protected FastDFSClientPool fastDFSClientPool(){
    35. GenericObjectPoolConfig<FastdfsClient> config = new GenericObjectPoolConfig<>();
    36. //链接池中最大连接数,默认为8
    37. config.setMaxTotal(8);
    38. //链接池中最大空闲的连接数,默认也为8
    39. config.setMaxIdle(8);
    40. //连接池中最少空闲的连接数,默认为0
    41. config.setMinIdle(0);
    42. //当这个值为true的时候,maxWaitMillis参数才能生效。为false的时候,当连接池没资源,则立马抛异常。默认为true
    43. config.setBlockWhenExhausted(true);
    44. //默认false,borrow的时候检测是有有效,如果无效则从连接池中移除,并尝试继续获取
    45. config.setTestOnBorrow(true);
    46. //默认false,return的时候检测是有有效,如果无效则从连接池中移除,并尝试继续获取
    47. config.setTestOnReturn(true);
    48. //默认false,在evictor线程里头,当evictionPolicy.evict方法返回false时,而且testWhileIdle为true的时候则检测是否有效,如果无效则移除
    49. config.setTestWhileIdle(true);
    50. //一定要关闭jmx,不然启动会报已经注册了某个jmx的错误
    51. config.setJmxEnabled(false);
    52. fastDFSClientPool = new FastDFSClientPool(fastdfsClientFactory, config);
    53. return fastDFSClientPool;
    54. }
    55. @PreDestroy
    56. public void destroy(){
    57. System.out.println("对象池关闭-start");
    58. if( null != fastDFSClientPool ){ fastDFSClientPool.close(); }
    59. System.out.println("对象池关闭-end");
    60. }
    61. }

    5.对象池的使用方式

    引入对象池,完成上传和下载

    1. @Autowired
    2. private FastDFSClientPool fastDFSClientPool;
    3. /**
    4. * 上传,使用对象池化模式,解决fastdfs不能多线程并发的问题
    5. * @param group_name
    6. * @param local_filename
    7. * @return
    8. */
    9. public String uploadWrapper(String group_name, String local_filename) {
    10. log.info("Upload FastDFS file - " + group_name + " - " + local_filename);
    11. FastdfsClient fastdfsClient = null;
    12. String uploadResult = null;
    13. try {
    14. fastdfsClient = fastDFSClientPool.borrowObject();
    15. if (fastdfsClient == null) {
    16. log.error("uploadWrapper FastdfsClient get error");
    17. return null;
    18. }
    19. uploadResult = fastdfsClient.upload_file1(group_name, local_filename, null, null);
    20. } catch (Exception e) {
    21. log.error(e.getMessage(), e);
    22. } finally {
    23. if(fastdfsClient != null){
    24. fastDFSClientPool.returnObject(fastdfsClient);
    25. }
    26. }
    27. return uploadResult;
    28. }
    29. /**
    30. * 下载,使用对象池化模式,解决fastdfs不能多线程并发的问题
    31. * @param filePath
    32. * @return
    33. */
    34. public byte[] downloadWrapper(String filePath) {
    35. log.info("Download FastDFS file - " + filePath);
    36. FastdfsClient fastdfsClient = null;
    37. byte[] fileContent = null;
    38. try {
    39. fastdfsClient = fastDFSClientPool.borrowObject();
    40. if (fastdfsClient == null) {
    41. log.error("downloadWrapper FastdfsClient get error");
    42. return null;
    43. }
    44. fileContent = fastdfsClient.download_file1(filePath);
    45. } catch (Exception e) {
    46. log.error(e.getMessage(), e);
    47. } finally {
    48. if(fastdfsClient != null){
    49. fastDFSClientPool.returnObject(fastdfsClient);
    50. }
    51. }
    52. return fileContent;
    53. }

  • 相关阅读:
    没想到吧,Spring中还有一招集合注入的写法
    Cyanine5-COOH,Cy5 COOH荧光染料146368-11-8星戈瑞
    Flutter教程之sqlite_wrapper新的 Dart 和 Flutter 库,用于 SQLite
    如此狂妄,自称高性能队列的Disruptor有啥来头?
    Linux开发工具(5)——git
    安全论坛和外包平台汇总
    使用VLC实现自动播放视频
    linux进程的调度
    基于ACS40核心板的串口图传设计
    零零信安-D&D数据泄露报警日报【第30期】
  • 原文地址:https://blog.csdn.net/weixin_42211693/article/details/125514395