(一)使用 c3p0

C3p0创建方式

c3p0有3种创建方式(1)直接实例化并配置comboPooledDataSource bean。(2)使用DataSources工厂类。(3)实现PoolBackedDataSource类(abstract类)。即实现自己的DataSource。

一、实例化并配置ComboPooledDataSource

ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver            
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("swaldman");                                  
cpds.setPassword("test-password");                                  
    
// the settings below are optional -- c3p0 can work with defaults
cpds.setMinPoolSize(5);                                     
cpds.setAcquireIncrement(5);
cpds.setMaxPoolSize(20);
    
// The DataSource cpds is now a fully configured and usable pooled DataSource

If you obtain a DataSource by instantiating a ComboPooledDataSource
, configure it by simply calling appropriate setter methods offered by that class before attempting a call to getConnection()
.

常用的最直接的方式是实例化ComboPooledDataSource。这是一个JavaBean风格的类,提供一个public,无参的构造器。配置参数至少要求配置jdbcUrl

c3p0支持以name命名的数据源。ComboPooledDataSource提供一个String的构造器,传入name即可。

ComboPooledDataSource cpds = new ComboPooledDataSource("intergalactoApp");

二、使用DataSources facotry工厂类

另一种方法是通过DataSources工厂类创建unpooled DataSource数据源,并且可通过unpooled DataSource创建pooled DataSource。

DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/testdb", 
                                                        "swaldman", 
                                                        "test-password");
DataSource ds_pooled = DataSources.pooledDataSource( ds_unpooled );

自定义配置项
指定一个Map存放配置项,使用pooledDataSource重载方法。

Map overrides = new HashMap();
overrides.put("maxStatements", "200");         //Stringified property values work
overrides.put("maxPoolSize", new Integer(50)); //"boxed primitives" also work

// create the PooledDataSource using the default configuration and our overrides
ds_pooled = DataSources.pooledDataSource( ds_unpooled, overrides ); 

为数据源指定名字
pooledDataSource重在方法提供命名name

ds_pooled = DataSources.pooledDataSource( ds_unpooled, "intergalactoApp", overrides ); 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,169评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,993评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,806评论 18 399
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,774评论 0 4
  • Spark SQL, DataFrames and Datasets Guide Overview SQL Dat...
    Joyyx阅读 8,359评论 0 16