SpringBoot整合Druid数据源的方法实现,可以分为以下几个步骤:
步骤一:添加Druid和jdbc依赖
在pom.xml文件中,添加以下两个依赖
<!--Druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<!--jdbc驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
步骤二:配置Druid数据源
在application.properties/yml文件中添加以下配置项
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#Druid配置
#监控地址
spring.datasource.druid.stat-view-servlet.allow=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
#用户名和密码
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
#IP白名单(没有配置或者为空,则允许所有访问)
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
#IP黑名单(存在共同时,deny优先于allow)
spring.datasource.druid.stat-view-servlet.deny=192.168.1.73
步骤三:创建数据库连接池
在代码中,通过注解@Configuration
创建数据源对象,并注入到spring容器中
@Configuration
public class DruidDBConfig {
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Bean
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(10);
datasource.setMinIdle(10);
datasource.setMaxActive(50);
datasource.setMaxWait(60000);
datasource.setTimeBetweenEvictionRunsMillis(60000);
datasource.setValidationQuery("SELECT 1 FROM DUAL");
datasource.setTestWhileIdle(true);
datasource.setTestOnBorrow(false);
datasource.setTestOnReturn(false);
datasource.setPoolPreparedStatements(true);
datasource.setMaxPoolPreparedStatementPerConnectionSize(50);
try {
datasource.setFilters("stat,wall,slf4j");
} catch (SQLException e) {
e.printStackTrace();
}
return datasource;
}
}
步骤四:测试连接
在代码中,创建一个测试Controller,测试是否能成功连接。
@RestController
public class HelloController {
@Autowired
private DataSource dataSource;
@RequestMapping("/hello")
String index() {
try {
Connection connection = dataSource.getConnection();
return "Hello Spring Boot and Druid!" + connection.getMetaData().getDatabaseProductName();
} catch (SQLException e) {
e.printStackTrace();
}
return "Hello Spring Boot and Druid!";
}
}
测试连接,访问url:http://localhost:8080/hello
如果连接成功,则会显示以下内容:
Hello Spring Boot and Druid!MySQL
示例一:
以下是一个完整的SpringBoot整合Druid数据源实现的示例,供参考:
pom.xml文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
</dependencies>
application.yml文件
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# Druid配置
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=60000
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.minEvictableIdleTimeMillis=30000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.druid.filters=stat,wall
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html
连接测试Controller
@RestController
public class HelloController {
@Autowired
private DataSource dataSource;
@RequestMapping("/hello")
public String index() throws SQLException {
Connection connection = dataSource.getConnection();
DatabaseMetaData metaData = connection.getMetaData();
String productName = metaData.getDatabaseProductName();
String productVersion = metaData.getDatabaseProductVersion();
return "Hello Spring Boot and Druid!数据库类型: "+productName+",版本: "+productVersion;
}
}
此示例中,当请求url:http://localhost:8080/hello时,会返回以下内容:
Hello Spring Boot and Druid!数据库类型: MySQL,版本: 5.6.39
示例二:
以下是一个完整的SpringBoot整合Druid数据源实现的示例,供参考:
pom.xml文件中添加以下依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
<!-- 集成 druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
<dependency><!-- mysql驱动 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
</dependencies>
application.yml文件
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimeZone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# Druid监控页面
spring.datasource.druid.stat.enable=true
# Druid连接池监控
spring.datasource.druid.filters=stat,wall,log4j2
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
server.servlet.context-path=/druid
Druid数据源配置类
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSource druidDataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "admin");
servletRegistrationBean.addInitParameter("resetEnable","false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");//添加过滤规则
filterRegistrationBean.addInitParameter("exclusions","*.jpg,*.png,*.gif,*.ico,/druid/*");//过滤掉静态资源请求和Druid的请求
return filterRegistrationBean;
}
}
测试Controller
@RestController
@RequestMapping("/druid")
public class TestController {
private static final String[] USER_NAMES = {"user1", "user2", "user3", "user4"};
private static final String[] AGES = {"22", "23", "24", "25", "26", "27", "28"};
@Autowired
private DataSource dataSource;
private Random random = new Random(System.currentTimeMillis());
@RequestMapping("/insertUser")
public String index() {
Connection connection = null;
PreparedStatement preparedStatement = null;
int row = 0;
String sql = "INSERT INTO user(name, age) VALUES (?, ?)";
try {
connection = dataSource.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, USER_NAMES[random.nextInt(USER_NAMES.length)]);
preparedStatement.setInt(2, Integer.valueOf(AGES[random.nextInt(AGES.length)]));
row = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return "成功插入[" + row + "]条用户数据";
}
}
此示例中,当请求url:http://localhost:8080/druid/insertUser时,会返回以下内容:
成功插入[1]条用户数据
并且,访问http://localhost:8080/druid,可以进入Druid监控页面,查看连接池的状态和信息。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot整合Druid数据源的方法实现 - Python技术站