package com.zy.acs.manager.core.service.astart; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Slf4j @Component public class NavigateNodePool { private ObjectPool pool; @PostConstruct public void init() { GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); config.setMaxTotal(30000); // 配置池的最大对象数量 config.setMinIdle(30000); // 最小空闲对象数,可以根据需求调整 config.setMaxIdle(30000); // 最大空闲对象数,可以根据需求调整 config.setBlockWhenExhausted(true); // 池耗尽时阻塞 config.setMaxWaitMillis(1000); // 池耗尽时最大等待时间 pool = new GenericObjectPool<>(new NavigateNodeFactory(), config); } // 获取对象 public NavigateNode borrowObject() { try { // System.out.println("numActive:" + pool.getNumActive()); // System.out.println("numIdle:" + pool.getNumIdle()); return pool.borrowObject(); } catch (Exception e) { log.error("borrowObject", e); throw new RuntimeException("Failed to borrow NavigateNode from pool", e); } } // 归还对象 public void returnObject(NavigateNode node) { if (node != null) { try { pool.returnObject(node); System.out.println("numIdle:" + pool.getNumIdle()); } catch (Exception e) { log.error("returnObject", e); // 如果归还失败,可以选择销毁对象 try { pool.invalidateObject(node); } catch (Exception ex) { throw new RuntimeException(ex); } } } } // 销毁对象池 public void close() { try { pool.close(); } catch (Exception e) { log.error("close", e); } } }