java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > @RequestController之数据源与连接池

@RequestController之数据源与连接池使用及说明

作者:追JAVA的小菜鸟

文章总结:介绍了Spring MVC中的@Controller和@ResponseBody注解以及@RequestMapping注解的使用方法,详细讲解了数据源、连接池的概念及其在Java项目中的应用,包括JNDI、DBCP、C3P0和Druid等连接池的配置和特点

一、@RequestController————类

@Controller————类

@ResponseBody————类/方法

@RequestMapping————方法(必需!!)

二、数据源与连接池

JNDI

Tomcat服务器在启动时可以创建一个连接到某种数据库系统的数据源DataSource对象,并将该数据源对象绑定到JNDI环境中,以后在这个Tomcat服务器中运行的Servlet和JSP程序就可以从JNDI环境中查询出这个数据源对象进行使用。

数据源DataSource

类似于通过指定文件名称可以在文件系统中找到文件一样,通过提供正确的数据源名称,能找到相应的数据库连接。算是对数据库的一个抽象映射。

连接池

连接池分类

1. DBCP

DBCP配置文件——dbcp.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true&useServerPrepStmts=false
username=root
password=abc123
2. C3P0

获取方式

//使用C3P0数据库连接池的配置文件方式,获取数据库的连接:推荐
private static DataSource cpds = new ComboPooledDataSource("helloc3p0");
public static Connection getConnection2() throws SQLException{
	Connection conn = cpds.getConnection();
	return conn;
}

c3p0配置文件——c3p0.properties

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<named-config name="helloc3p0">
		<!-- 获取连接的4个基本信息 -->
		<property name="user">root</property>
		<property name="password">abc123</property>
		<property name="jdbcUrl">jdbc:mysql:///test</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		
		<!-- 涉及到数据库连接池的管理的相关属性的设置 -->
		<!-- 若数据库中连接数不足时, 一次向数据库服务器申请多少个连接 -->
		<property name="acquireIncrement">5</property>
		<!-- 初始化数据库连接池时连接的数量 -->
		<property name="initialPoolSize">5</property>
		<!-- 数据库连接池中的最小的数据库连接数 -->
		<property name="minPoolSize">5</property>
		<!-- 数据库连接池中的最大的数据库连接数 -->
		<property name="maxPoolSize">10</property>
		<!-- C3P0 数据库连接池可以维护的 Statement 的个数 -->
		<property name="maxStatements">20</property>
		<!-- 每个连接同时可以使用的 Statement 对象的个数 -->
		<property name="maxStatementsPerConnection">5</property>

	</named-config>
</c3p0-config>
3.Druid

Druid配置文件——druid.properties

url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
username=root
password=123456
driverClassName=com.mysql.jdbc.Driver

initialSize=10
maxActive=20
maxWait=1000
filters=wall

总结

连接池就像数据源的代理人,我们需要连接直接找连接池要,不用的连接也是直接还给连接池。

获取数据时,通过找到JNDI,找到连接池,再找到连接对象和对应的数据库。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文