springboot使用druid的例子
时间: 2023-10-24 08:05:50 浏览: 157
springboot 实例
以下是一个简单的Spring Boot项目使用Druid连接池的例子:
1. 在pom.xml中添加Druid和JDBC依赖
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
```
2. 在application.yml中配置Druid连接池
```yaml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: password
type: com.alibaba.druid.pool.DruidDataSource
# 配置Druid连接池
druid:
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位毫秒
min-evictable-idle-time-millis: 300000
# 配置连接池中连接的使用情况,可以用来监控和统计连接池的使用情况
log-abandoned: true
# 配置从连接池中取出连接时是否进行有效性检查
test-on-borrow: true
# 配置归还连接时是否进行有效性检查
test-on-return: false
# 配置是否缓存preparedStatement,也就是PSCache
pool-prepared-statements: true
# 配置每个连接上PSCache的大小
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters
filters: stat,wall,log4j
# 配置DruidStatViewServlet和DruidWebStatFilter
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: false
web-stat-filter:
enabled: true
url-pattern: /druid/*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
```
3. 创建一个数据访问对象(DAO)类,使用Druid连接池获取数据库连接并执行SQL查询
```java
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
public class UserDao {
@Autowired
private DruidDataSource dataSource;
private Connection conn = null;
@PostConstruct
public void init() {
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
public User getUserById(int id) {
User user = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM users WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return user;
}
}
```
4. 创建一个控制器(Controller)类,使用UserDao查询数据库并返回查询结果
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserDao userDao;
@GetMapping("/users/{id}")
public User getUserById(@PathVariable int id) {
return userDao.getUserById(id);
}
}
```
5. 运行Spring Boot应用程序并访问http://localhost:8080/users/1,应该会返回一个JSON格式的用户对象。
阅读全文