spring boot之Druid连接池07
程序员文章站
2022-05-23 15:05:49
...
spring boot之Druid连接池07
整合Druid数据源
第一步导入Druid连接池的依赖
通过maven仓库的官网搜素Druid连接池的依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
修改application.yaml的数据源类型
spring:
datasource:
username: root
password: 111111
url: jdbc:mysql:///chucun?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
通过测试类可以打印出数据源的类名和连接
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@SpringBootTest
class SpringBootJdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
Connection conn = dataSource.getConnection();
System.out.println(conn);
System.out.println(dataSource.getClass());
}
}
可以通过创建一个配置类来进行操作
导入druid数据源
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
上一篇: JavaScript-面向对象与原型
推荐阅读
-
Spring Boot → 07:错误处理机制
-
spring-boot-2.0.3不一样系列之源码篇 - run方法(三)之createApplicationContext,绝对有值得你看的地方
-
详解Spring Boot实战之Filter实现使用JWT进行接口认证
-
详解Spring Boot实战之单元测试
-
spring-boot-2.0.3不一样系列之番外篇 - 自定义session管理,绝对有值得你看的地方
-
JSP Spring中Druid连接池配置详解
-
荐 Java——数据库编程JDBC之数据库连接池技术(C3P0与Druid,提供了Druid的工具类)
-
spring-boot-2.0.3之redis缓存实现,不是你想的那样哦!
-
荐 微服务之Spring Boot2—降低开发复杂度之面向切面AOP
-
spring boot之入门配置(一)