java的连接池c3p0、DBCP等等好多好多,优劣网上一大堆。在这我用的阿里的Druid连接Mysql5.7以上版本采坑。
安装Mysq6以上版本window版的比较容易,但是linux版的真是麻烦死了,这里安装linux的自己网上搜吧一大堆。我这里使用的是Mysql8.0的。
首先看一下Druid的配置信息
## 数据源配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/sip?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
##com.mysql.jdbc.Driver
#mybatis 配置
mybatis.typeAliasesPackage=com.example.userservice.model
mybatis.mapperLocations=classpath:com/example/userservice/model/*Mapper.xml
#durid登陆账号密码
druid.loginUsername=root
druid.loginPassword=123456
# 下面为连接池的补充设置,应用到上面所有数据源中
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙,防止sql注入
spring.datasource.filters=stat,wall,log4j
spring.datasource.logSlowSql=true
这个不全,详细介绍请看 druid 详细配置 - u010085393的博客 - CSDN博客
先pom中增加jar包,druid不说,mysql-connector用的8.0 ,mybatis。
配置文件修改,mysql6以上版本用的driver是com.mysql.cj.jdbc.Driver这个要注意。
url连接参数有些变化 1:serverTimezone设置时区;2:useSSL=true 使用SSL连接方式;3:如果使用generator生成Mapper的时候一定要加上nullCatalogMeansCurrent=true;
jdbc:mysql://127.0.0.1:3306/sip?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true
然后创建DruidConfig 添加注解@Configuration注入
配置代码如下,其中druidServlet 是Druid的监控页面
package
生成mapper这里我用maven-generator 生成。pom添加plugin
maven运行 mybatis-generator:generate 生成
注意上面配置项中的路径别错了
#mybatis 配置
mybatis.typeAliasesPackage=com.example.userservice.model mybatis.mapperLocations=classpath:com/example/userservice/model/*Mapper.xml
在spring boot启动类添加扫描注解
@MapperScan("com.example.userservice.model")
然后在service添加新接口getAllUsers,添加实现主任Mapper,这里Mapper就是Dao
Example类是Mybatis参数封装,要是不想generate生成的化在table标签中设置
<table tableName="user"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
selectByExampleQueryId="false"
enableSelectByExample="false"
></table>
然后controller添加一个restful接口
ok 打完收工。看看效果吧。
到这完事( ̄▽ ̄)"