使用docker快速搭建mysql:
sleeber@ubuntu-134:~$ docker run --name mysql-5.7 -p 3306:3306 -v /home/sleeber/dbDatas/mysql:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=ubuntu -d mysql:5.7
6a18e1346b06c76009309823ae7148cff75c50106f9aeffaa2b5e9192f795858
sleeber@ubuntu-134:~$ docker exec -it 6a18e13 bash
root@6a18e1346b06:/# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.31 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
mysql>
初始化数据库
--创建数据库
create schema nuts default character set utf8 collate utf8_general_ci;
采用create schema和create database创建数据库的效果一样。
--创建用户
create user 'ann'@'%' identified by 'sleeber';
密码8位以上,包括:大写字母、小写字母、数字、特殊字符
%:匹配所有主机,该地方还可以设置成‘localhost’,代表只能本地访问,例如root账户默认为‘localhost‘
--用户授权数据库
grant select,insert,update,delete,create,drop,alter on nuts.* to ann;
* 代表整个数据库表
--立即启用修改
flush privileges ;
--取消用户所有数据库(表)的所有权限
revoke all on *.* from tester;
--删除用户
delete from mysql.user where user='tester';
--删除数据库
drop database [schema名称|数据库名称];
模块 | 子模块 | 说明 |
nuts.springboot.boot | 工程启动引导项目 | |
nuts-springboot-listener | actuator admin项目 | |
components | ||
nuts-springboot-dbpool | 数据库连接池组件 | |
nuts-springboot-log4j2 | 使用log4j2作为日志组件 | |
nuts-springboot-logback | springboot默认日志组件 | |
endpoints | 后端api响应接口 | |
nuts-springboot-clover | 模板项目后端 | |
nuts-springboot-home | 统一异常处理、统一返回结构 | |
kernels | 工程内核模型 | |
nuts-springboot-core | 核心模型 | |
在rootProjet中增加 config.gradle插件,实现可配置的dependency
# build.gradle文件
apply from: 'config.gradle'
新增config.gradle文件:
ext {
dependencies=[
"mysql-driver":"mysql:mysql-connector-java",
"hikaricp-pool":"com.zaxxer:HikariCP:3.4.5",
"druid-pool":"com.alibaba:druid:1.1.23",
"tomcat-pool":"org.apache.tomcat:tomcat-jdbc:8.5.57",
"dbcp2-pool":"org.apache.commons:commons-dbcp2:2.7.0",
"c3p0-pool":"com.mchange:c3p0:0.9.5.5"
]
}
在子模块dbpool项目中的dbpool.gradle以下面的方式引入需要的依赖:
dependencies {
implementation('org.springframework.boot:spring-boot-starter-jdbc:2.2.9.RELEASE') {
exclude group: 'com.zaxxer', module: 'HikariCP'
}
// MySql数据库驱动
implementation rootProject.ext.dependencies["mysql-driver"]
implementation rootProject.ext.dependencies["druid-pool"]
}
增加MysqlDbPoolConfiguration类,用于项目初始化数据库连接池:
@ConditionalOnClass(name = {"com.mysql.cj.jdbc.Driver"})
@Configuration
public class MysqlDbPoolConfiguration {
@ConditionalOnClass(name = {"com.zaxxer.hikari.HikariDataSource"})
@Bean(destroyMethod = "close", name = "mysqlJdbcDataSource")
@ConfigurationProperties("spring.datasource.hikari")
public DataSource getHikariCPDatabasePool() {
return DataSourceBuilder.create().build();
}
@ConditionalOnClass(name = {"com.alibaba.druid.pool.DruidDataSource"})
@Bean(destroyMethod = "close", name = "mysqlJdbcDataSource")
@ConfigurationProperties("spring.datasource.druid")
public DataSource getDruidDatabasePool() {
return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
}
// @ConditionalOnClass(name = {"org.apache.tomcat.jdbc.pool.DataSource"})
// @Bean(destroyMethod = "close", name = "mysqlJdbcDataSource")
// @ConfigurationProperties("spring.datasource.tomcat")
// public DataSource getTomcatDatabasePool() {
// return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build();
// }
// @ConditionalOnClass(name = {"org.apache.commons.dbcp2.BasicDataSource"})
// @Bean(destroyMethod = "close", name = "mysqlJdbcDataSource")
// @ConfigurationProperties("spring.datasource.dbcp2")
// public DataSource getDbcp2DatabasePool() {
// return DataSourceBuilder.create().type(org.apache.commons.dbcp2.BasicDataSource.class).build();
// }
// @ConditionalOnClass(name = {"com.mchange.v2.c3p0.ComboPooledDataSource"})
// @Bean(destroyMethod = "close", name = "mysqlJdbcDataSource")
// @ConfigurationProperties("spring.datasource.c3p0")
// public DataSource getC3p0DatabasePool() {
// return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
// }
@ConditionalOnBean(value = {javax.sql.DataSource.class})
@Bean(name = "mysqlJdbcTemplate")
public JdbcTemplate getMysqlJdbcTemplate(@Autowired DataSource mysqlJdbcDataSource) {
return new JdbcTemplate(mysqlJdbcDataSource);
}
}
为了测试数据库连接池,使用SpringBootTest进行单元测试:
@SpringBootTest(classes = {MysqlDbPoolConfiguration.class})
class MysqlDbPoolConfigurationTest extends AbstractSpringBootTest {
private static final Logger logger = LoggerFactory.getLogger(MysqlDbPoolConfigurationTest.class);
@Test
void getMysqlJdbcTemplate() {
JdbcTemplate jdbcTemplate = webApplicationContext.getBean(JdbcTemplate.class);
Assert.isInstanceOf(JdbcTemplate.class, jdbcTemplate, "SpringBoot数据库模板jdbcTemplate对象不能为空");
}
@Test
void getMysqlJdbcDataSource() {
DataSource dataSource = webApplicationContext.getBean(DataSource.class);
Assert.isInstanceOf(DataSource.class, dataSource,"数据库数据源对象不能为空");
}
}
在测试数据库查询语句测试时,报Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: url not set
@SpringBootTest(classes = {MysqlDbPoolConfiguration.class})
public class JdbcTemplateTest extends AbstractSpringBootTest {
private static final Logger logger = LoggerFactory.getLogger(JdbcTemplateTest.class);
@Test
public void getAllUser() {
JdbcTemplate jdbcTemplate = webApplicationContext.getBean(JdbcTemplate.class);
Assert.isTrue(jdbcTemplate.queryForList("Select 3", Integer.class).get(0).equals(3), "数据库连接异常");
}
}
查看输出,没看正常挂载项目配置yaml文件,怀疑@SpringBootTest(classes = {MysqlDbPoolConfiguration.class})方式,可能比@SpringBootApplication少了配置文件的load。
那@SpringBootTest(classes = {MysqlDbPoolConfiguration.class})改为@SpringBootTest,并增加一个测试引导类
@SpringBootApplication
public class SpringBootTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootTestApplication.class, args);
}
}
单元测试可以正常运行。
最终dbpool模块结构:
————————————————
Github项目 https://github.com/HazelNutsWorkGroup/nuts.springboot.single ,
Gitee项目 https://gitee.com/sleeber/nuts.springboot.single
欢迎大家交流