一、整合JDBC
第一步:创建springboot项目
创建springboot项目时勾选如图所示依赖。
第二步:配置连接
这里使用的是ymal配置文件。
配置代码:
spring:
datasource:
username: root
password: '000000'
url: jdbc:mysql://127.0.0.1:3306/testjdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
注意使用的mysql驱动是8.0.0以上版本的,springboot2.4版本中password中密码要加单引号。
第三步:测试连接
创建一个控制器并且写一个查询所有数据并将查询的数据直接输出到页面上。
@RestController
public class JDBCController {
@Autowired
private JdbcTemplate jdbcTemplate;
@GetMapping("/list")
public List<Map<String,Object>> getAll(){
String sql = "select * from tb_user";
List<Map<String, Object>> list_map = jdbcTemplate.queryForList(sql);
return list_map;
}
}
启动项目访问http://localhost:8080/list,数据成功展示,表示整合JDBC成功。
二、整合Druid
第一步:添加ymal配置
整合JDBC默认的是Hikari是目前速度最快的数据源,在整合了JDBC的配置文件中,指定Druid数据源。
spring:
datasource:
username: root
password: '000000'
url: jdbc:mysql://127.0.0.1:3306/testjdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
# 指定数据类型
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,Log
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
第二步:导入Druid依赖与log4j的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
第三步:自己配置Druid
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//后台监控 web.xml
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
//后台需要有人监控、账号密码配置
HashMap<String,String> map = new HashMap<>();
map.put("loginUsername","admin");
map.put("loginPassword","000000");
//允许谁可以访问
map.put("allow","");
bean.setInitParameters(map);
return bean;
}
}
第四步:启动项目测试
访问:http://localhost:8080/druid,显示如下登录页面。
输入配置文件DruidConfig中自己配置的账号密码登录。
登录成功进入日志监控首页