BoneCP数据库连接池源码解析

传统的连接池比如proxool,会使用List存放所有的连接,通过读写锁来修改连接的状态,标示该连接是否是可用,而BoneCP采用了分区的方式提高了获取数据库连接的并发性,类似ConcurrentHashMap解决并发问题的思想。

 

下面看下主要的几个类:

  • BoneCPDataSource:实现了DataSource接口,接收数据库的配置并对外提供获取数据库连接的功能,第一次获取连接时会初始化连接池BoneCP对象。
public Connection getConnection() throws SQLException {
		
		FinalWrapper<BoneCP> wrapper = this.pool;

        if (wrapper == null) {
                synchronized (this) {
                        if (this.pool == null) {
                        	try{
                        		if (this.getDriverClass() != null){
                        			loadClass(this.getDriverClass());
                        		}
    					
                        		logger.debug(this.toString());
                        		this.pool = new FinalWrapper<BoneCP>(new BoneCP(this));
    				    
                        	} catch (ClassNotFoundException e) {
                        		throw new SQLException(PoolUtil.stringifyException(e));
                        	}
                        }

                        wrapper = this.pool;
                } 
        }

        return wrapper.value.getConnection();
     }

 

  • BoneCp:负责连接池的初始化、获取数据库连接的功能,初始化流程:
  1. 根据配置文件中分区的个数创建ConnectionPartition对象,并根据配置文件中的最小连接数为每个分区创建连接
  2. 为每个ConnectionPartition创建三个线程,PoolWatchThread用于数据库新连接的建立,ConnectionMaxAgeThread用于连接最大存活时间的检查,ConnectionTesterThread最大空闲时间的检查
    	public BoneCP(BoneCPConfig config) throws SQLException {
    		Class<?> clazz;
    		try {
    			jvmMajorVersion = 5;
    			clazz = Class.forName(connectionClass , true, config.getClassLoader());
    			clazz.getMethod("createClob"); // since 1.6
    			jvmMajorVersion = 6;
    			clazz.getMethod("getNetworkTimeout"); // since 1.7
    			jvmMajorVersion = 7;
    		} catch (Exception e) {
    			// do nothing
    		}
    		try {
    			this.config = Preconditions.checkNotNull(config).clone(); // immutable
    		} catch (CloneNotSupportedException e1) {
    			throw new SQLException("Cloning of the config failed");
    		}
    		this.config.sanitize();
    
    		this.statisticsEnabled = config.isStatisticsEnabled();
    		this.closeConnectionWatchTimeoutInMs = config.getCloseConnectionWatchTimeoutInMs();
    		this.poolAvailabilityThreshold = config.getPoolAvailabilityThreshold();
    		this.connectionTimeoutInMs = config.getConnectionTimeoutInMs();
    
    		if (this.connectionTimeoutInMs == 0){
    			this.connectionTimeoutInMs = Long.MAX_VALUE;
    		}
    		this.nullOnConnectionTimeout = config.isNullOnConnectionTimeout();
    		this.resetConnectionOnClose = config.isResetConnectionOnClose();
    		this.clientInfo = jvmMajorVersion > 5  ? config.getClientInfo() : null;
    		AcquireFailConfig acquireConfig = new AcquireFailConfig();
    		acquireConfig.setAcquireRetryAttempts(new AtomicInteger(0));
    		acquireConfig.setAcquireRetryDelayInMs(0);
    		acquireConfig.setLogMessage("Failed to obtain initial connection");
    
    		if (!config.isLazyInit()){
    			try{
    				Connection sanityConnection = obtainRawInternalConnection();
    				sanityConnection.close();
    			} catch (Exception e){
    				if (config.getConnectionHook() != null){
    					config.getConnectionHook().onAcquireFail(e, acquireConfig);
    				}
    				throw PoolUtil.generateSQLException(String.format(ERROR_TEST_CONNECTION, config.getJdbcUrl(), config.getUsername(), PoolUtil.stringifyException(e)), e);
    
    			}
    		}
    		if (!config.isDisableConnectionTracking()){
    			this.finalizableRefQueue = new FinalizableReferenceQueue();
    		}
    
    		this.asyncExecutor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    
    		this.config = config;
    		this.partitions = new ConnectionPartition[config.getPartitionCount()];
    		String suffix = "";
    
    		if (config.getPoolName()!=null) {
    			suffix="-"+config.getPoolName();
    		}
    
    
    		this.keepAliveScheduler =  Executors.newScheduledThreadPool(config.getPartitionCount(), new CustomThreadFactory("BoneCP-keep-alive-scheduler"+suffix, true));
    		this.maxAliveScheduler =  Executors.newScheduledThreadPool(config.getPartitionCount(), new CustomThreadFactory("BoneCP-max-alive-scheduler"+suffix, true));
    		this.connectionsScheduler =  Executors.newFixedThreadPool(config.getPartitionCount(), new CustomThreadFactory("BoneCP-pool-watch-thread"+suffix, true));
    
    		this.partitionCount = config.getPartitionCount();
    		this.closeConnectionWatch = config.isCloseConnectionWatch();
    		this.cachedPoolStrategy = config.getPoolStrategy() != null && config.getPoolStrategy().equalsIgnoreCase("CACHED");
    		if (this.cachedPoolStrategy){
    			this.connectionStrategy = new CachedConnectionStrategy(this, new DefaultConnectionStrategy(this));
    		} else {
    			this.connectionStrategy = new DefaultConnectionStrategy(this);
    		}
    		boolean queueLIFO = config.getServiceOrder() != null && config.getServiceOrder().equalsIgnoreCase("LIFO");
    		if (this.closeConnectionWatch){
    			logger.warn(THREAD_CLOSE_CONNECTION_WARNING);
    			this.closeConnectionExecutor =  Executors.newCachedThreadPool(new CustomThreadFactory("BoneCP-connection-watch-thread"+suffix, true));
    
    		}
    		for (int p=0; p < config.getPartitionCount(); p++){
    
    			ConnectionPartition connectionPartition = new ConnectionPartition(this);
    			this.partitions[p]=connectionPartition;
    			BlockingQueue<ConnectionHandle> connectionHandles = new LinkedBlockingQueue<ConnectionHandle>(this.config.getMaxConnectionsPerPartition());
    
    			this.partitions[p].setFreeConnections(connectionHandles);
    
    			if (!config.isLazyInit()){
    				for (int i=0; i < config.getMinConnectionsPerPartition(); i++){
    					this.partitions[p].addFreeConnection(new ConnectionHandle(null, this.partitions[p], this, false));
    				}
    
    			}
    
    
    			if (config.getIdleConnectionTestPeriod(TimeUnit.SECONDS) > 0 || config.getIdleMaxAge(TimeUnit.SECONDS) > 0){
    
    				final Runnable connectionTester = new ConnectionTesterThread(connectionPartition, this.keepAliveScheduler, this, config.getIdleMaxAge(TimeUnit.MILLISECONDS), config.getIdleConnectionTestPeriod(TimeUnit.MILLISECONDS), queueLIFO);
    				long delayInSeconds = config.getIdleConnectionTestPeriod(TimeUnit.SECONDS);
    				if (delayInSeconds == 0L){
    					delayInSeconds = config.getIdleMaxAge(TimeUnit.SECONDS);
    				}
    				if (config.getIdleMaxAge(TimeUnit.SECONDS) < delayInSeconds
    						&& config.getIdleConnectionTestPeriod(TimeUnit.SECONDS) != 0 
    						&& config.getIdleMaxAge(TimeUnit.SECONDS) != 0){
    					delayInSeconds = config.getIdleMaxAge(TimeUnit.SECONDS);
    				}
    				this.keepAliveScheduler.schedule(connectionTester, delayInSeconds, TimeUnit.SECONDS);
    			}
    
    
    			if (config.getMaxConnectionAgeInSeconds() > 0){
    				final Runnable connectionMaxAgeTester = new ConnectionMaxAgeThread(connectionPartition, this.maxAliveScheduler, this, config.getMaxConnectionAge(TimeUnit.MILLISECONDS), queueLIFO);
    				this.maxAliveScheduler.schedule(connectionMaxAgeTester, config.getMaxConnectionAgeInSeconds(), TimeUnit.SECONDS);
    			}
    			// watch this partition for low no of threads
    			this.connectionsScheduler.execute(new PoolWatchThread(connectionPartition, this));
    		}
    
    		if (!this.config.isDisableJMX()){
    			registerUnregisterJMX(true);
    		}
    
    
    	}
     当需要获取连接时采用策略模式从BoneCP定义的ConnectionPartition数组中随机选择一个获取连接,如果获取不到会尝试其它ConnectionPartition。创建连接的方式是直接使用java中的DriverManager来创建数据库连接,并放到对应ConnectionPartition的队列中。
  • ConnectionPartition:通过LinkedBlockingQueue维护数据库连接,获取连接时从队列中取出一个

  • ConnectionHandle:实现了Connection接口,对于close操作会将连接放回到指定ConnectionPartition的LinkedBlockingQueue队列中,这样就能复用连接,同时缓存创建的statement

  • ConnectionTesterThread和ConnectionMaxAgeThread会根据配置文件定时执行,在执行时会将ConnectionPartition中的LinkedBlockingQueue一次取出,判断连接的各种状态,符合条件后再放回LinkedBlockingQueue中,这期间会对连接池有比较大的性能影响

猜你喜欢

转载自lishichang.iteye.com/blog/2269433