1.关于Druid
Druid是阿里团队开源的高性能数据库连接池,国内使用广泛,特别是在监控sql和数 据库性能方面非常强大。
连接池能有效节省数据库连接消耗,且对高写入、实时性要求高的业务非常合适。
2.引入依赖到pom.xml中。
<!--Druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
3.然后在application.yml中设置相关配置
其中最重要的是:
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/Auction?serverTimezone=UTC&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
这样就不会使用Springboot默认的连接池
4.配置数据库监控。
@Configuration
public class Druidconfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
return new DruidDataSource();
}
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
//后台需要有人登陆,账号密码配置
HashMap<String,String> stringHashMap = new HashMap<>();
//增加配置
stringHashMap.put("loginUsername","admin");//key值是固定的
stringHashMap.put("loginPassword","admin");
//允许谁可以访问
stringHashMap.put("allow","");
//禁止谁访问
stringHashMap.put("lss","192.168.200.159");//账号和ip地址
bean.setInitParameters(stringHashMap);
return bean;
}
}
到这里,关于 Druid 的配置就基本完成了
启动项目,浏览器访问 localhost:8080/druid