最好用的jdbc连接池莫过于druid
druid第一种连接方式:
DruidDataSource dds = new DruidDataSource();
try {
dds.setUrl("jdbc:mysql://localhost:3306/");
dds.setUsername("root");
dds.setPassword("admin");
dds.setDriverClassName("com.mysql.cj.jdbc.Driver");
System.out.println(dds.getConnection());
} catch (SQLException e) {
e.printStackTrace();
}
第二种连接方式:使用配置文件
DruidDataSource dds = new DruidDataSource();
Properties p = new Properties();
//加载提前写好的配置文件
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
try {
p.load(is);
//druid加载文件内容
dds.setConnectProperties(p);
System.out.println(dds.getConnection());
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
配置文件内容:
必须按这个配置名填写druid.
druid.url=jdbc:mysql://localhost:3306/db1
druid.username=root
druid.password=admin
druid.driverClassName=com.mysql.cj.jdbc.Driver
初始化创建连接数
druid.initialSize=2
最大连接数
druid.maxActive=8
启用数据监控监控
druid.filters=stat config
连接方式说完之后开始web监控
启用之前要开启监控,如配置文件最后一行
然后配置web.xml过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>DruidWebStatFilter</filter-name>
<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
<init-param>
<param-name>exclusions</param-name>
<param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DruidWebStatFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
<init-param>
<!-- 允许清空统计数据 -->
<param-name>resetEnable</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<!-- 用户名 -->
<param-name>loginUsername</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<!-- 密码 -->
<param-name>loginPassword</param-name>
<param-value>123</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
然后开启服务器
输入自己设置的账号密码就能登录了
druid还带了加密解密工具 让人就算拿到了项目源码对于不懂的人也不知道数据库密码
DruidDataSource dds = new DruidDataSource();
ConfigTools cfg = new ConfigTools();
//使用默认公钥解密
String pwd = ConfigTools.decrypt( "CiY2mPqmsxJR6omIgyE42f4/8w2yJHYMaB2N8+84lZoN+tgnMGUYJTYTvrYf9vzZ3fzri8WcC69m8Ot+O5Vm5Q==");
//使用默认私钥加密 返回String
ConfigTools.encrypt("admin");
//获取一对公钥私钥 每次都不同 私钥加密 公钥解密
String[] ss = ConfigTools.genKeyPair(512);
//私钥
String s1 = ss[0];
//公钥
String s2 = ss[1];
System.out.println(s1);
System.out.println(s2);