Springboot 系列(九)使用 Spring JDBC 和 Druid 数据源监控

点赞再看,动力无限。Hello world : ) 微信搜「 程序猿阿朗 」。

本文 Github.com/niumoo/JavaNotes未读代码博客 已经收录,有很多知识点和系列文章。

前言

监控

作为一名 Java 开发者,相信对 JDBC(Java Data Base Connectivity)是不会陌生的,JDBC作为 Java 基础内容,它提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。下面演示下 Springboot 中如何使用 JDBC 操作,并配置使用 Druid 连接池,体验 Druid 对数据库操作强大的监控和扩展功能。Alibaba-Durid 官方手册点这里

1. 数据库准备

使用mysql数据库创建数据库 springboot,并在库中新建数据表 user 并新增两条信息。

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `password` varchar(32) NOT NULL,
  `skills` varchar(255) DEFAULT NULL,
  `username` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

# 新增数据
INSERT INTO `springboot`.`user`(`id`, `age`, `birthday`, `password`, `skills`, `username`) VALUES (1, 17, '2019-01-12 21:02:30', '123', 'Go', 'Darcy');
INSERT INTO `springboot`.`user`(`id`, `age`, `birthday`, `password`, `skills`, `username`) VALUES (3, 23, '2019-01-01 00:11:22', '456', 'Java', 'Chris');

2. 添加依赖

新建一个 Springboot项目,这里不说。添加依赖如下。

    <dependencies>
        <!-- spring jdbc 操作模版 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- springboot web开发 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- mysql 数据库连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 引入druid数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

3. 配置数据源信息

常规的 JDBC 配置不需要配置这么多内容,这里因为使用了 Druid 连接池,所以配置了 Druid 部分。对自动配置不理解的可以查看系列文章Springboot 系列(二)Spring Boot 配置文件

spring:
  datasource:
    username: root
    password: 123
    url: jdbc:mysql://127.0.0.1:3306/springboot?characterEncoding=utf-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.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
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

配置完毕之后,配置信息还不能绑定到 Druid数据源中,还需要新建一个配置类绑定数据源和配置信息。

/**
 * <p>
 * Druid 数据源配置
 *
 * @Author niujinpeng
 * @Date 2019/1/14 22:20
 */
@Configuration
public class DruidConfig {
    /**
     * 配置绑定
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druid() {
        return new DruidDataSource();
    }
}

到这里,数据源已经配置完毕,编写测试方法测试 druid 连接池是否生效。


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootDataJdbcApplicationTests {
    @Autowired
    DataSource dataSource;
    /**
     * 测试JDBC数据源
     * @throws SQLException
     */
    @Test
    public void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

运行看到 contextLoads 输出信息。

class com.alibaba.druid.pool.DruidDataSource
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2019-02-27 14:14:56.144  INFO 12860 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@3e104d4b

输出日志中的 com.alibaba.druid 说明 Druid 已经生效。

4. 使用 Spring-JDBC

传统的 JDBC 使用中,需要编写大量代码,从构造 PreparedStatement 到查询不胜其烦。面对这样的开发痛点,Spring 封装了 Spring-jdbc. 让我们使用 JdbcTemplate 即可轻松的操作数据库。Spring-jdbc 的详细使用不是这篇文章重点,只简单演示下是否生效。
编写控制器,查询一个 user 信息。

@RestController
public class JdbcController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @ResponseBody
    @GetMapping("/query")
    public Map<String, Object> map() {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * FROM user");
        return list.get(0);
    }
}

启动spring 项目,请求 /query 接口得到正常响应。

{
"id": 1,
"age": 17,
"birthday": "2019-01-12T13:02:30.000+0000",
"password": "123",
"skills": "Go",
"username": "Darcy"
}

可见 Spring-JDBC 已经从数据库中取出了数据信息。

5. 使用 Druid 监控

如果使用 Druid 连接池却不使用监控功能,那么就有点暴殄天物了。下面开始配置 Druid 的 SQL 监控功能。在上面写的 DruidConfig 配置类中增加配置 Druid 的 Servlet 和 Filter.

 	/**
     * Druid的servlet
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet());
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "123");
        initParams.put("allow","127.0.0.1");
        bean.setInitParameters(initParams);
        bean.setUrlMappings(Arrays.asList("/druid/*"));
        return bean;
    }
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter());
        HashMap<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "/css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

上面配置了 Druid 监控访问路径为 /druid、登录用户是 admin、登录密码是123、允许访问的IP是127.0.0.1 本机、不需要监控的请求是 /css/druid 开头的请求。

重新启动项目,访问测试 /query,然后访问 /durid 登录页。
登录页面

登录后可以看到 SQL 监控信息和 URL 监控等信息。
Sql监控
URL 监控。
URL监控

文章代码已经上传到 GitHub Spring Boot jdb

<完>

Hello world : ) 我是阿朗,一线技术工具人,认认真真写文章。

点赞的个个都是人才,不仅长得帅气好看,说话还好听。


文章持续更新,可以关注公众号「 程序猿阿朗 」或访问「未读代码博客 」。

回复【资料】有我准备的各系列知识点和必看书籍。

本文 Github.com/niumoo/JavaNotes 已经收录,有很多知识点和系列文章,欢迎Star。

等你好久

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot可以很方便地整合Druid数据,只需要在pom.xml中添加DruidJDBC依赖,然后在application.properties中配置Druid数据即可。 具体步骤如下: 1. 在pom.xml中添加DruidJDBC依赖: ``` <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> ``` 2. 在application.properties中配置Druid数据: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # Druid配置 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.initial-size=5 spring.datasource.druid.min-idle=5 spring.datasource.druid.max-active=20 spring.datasource.druid.test-on-borrow=true spring.datasource.druid.test-on-return=false spring.datasource.druid.test-while-idle=true spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.validation-query=SELECT 1 FROM DUAL spring.datasource.druid.filters=stat,wall,log4j spring.datasource.druid.max-wait=60000 spring.datasource.druid.pool-prepared-statements=true spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20 spring.datasource.druid.use-global-data-source-stat=true ``` 3. 在代码中使用Druid数据: ``` @Autowired private DataSource dataSource; ``` 以上就是整合Druid数据的步骤,希望对你有所帮助。 ### 回答2: SpringBoot是现在使用最广泛的Java框架之一,它提供了很多方便开发的功能和快捷的开发方式,其中整合Druid数据就是其中之一。 首先需要在pom.xml文件中引入druidjdbc相关的依赖,例如: ``` <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> ``` 接着,在application.properties文件中配置druid数据,例如: ``` # 数据配置 spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.filters=stat,wall,log4j spring.datasource.maxActive=20 spring.datasource.initialSize=1 spring.datasource.minIdle=3 spring.datasource.maxWait=60000 spring.datasource.timeBetweenEvictionRunsMillis=60000 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.poolPreparedStatements=true spring.datasource.maxOpenPreparedStatements=50 ``` 其中,spring.datasource.url是数据库连接字符串,spring.datasource.username和spring.datasource.password是数据库的用户名和密码,spring.datasource.driverClassName是数据库驱动的类名。其他参数是Druid连接池的相关配置,比如最大并发连接数、初始连接数、最小空闲连接数等。 然后,通过在@SpringBootApplication注解中加上@EnableTransactionManagement和@MapperScan注解来开启事务和扫描Mapper,例如: ``` @SpringBootApplication @EnableTransactionManagement @MapperScan(basePackages = "com.example.demo.dao") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 最后,在需要使用数据的地方注入DataSource,并使用JdbcTemplate来操作数据库,例如: ``` @Service public class UserServiceImpl implements UserService { @Autowired private DataSource dataSource; private JdbcTemplate jdbcTemplate; @PostConstruct public void init() { jdbcTemplate = new JdbcTemplate(dataSource); } @Override public User getUserById(int id) { String sql = "SELECT * FROM user WHERE id=?"; return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class)); } @Override public void saveUser(User user) { String sql = "INSERT INTO user(name, age, gender) VALUES(?, ?, ?)"; jdbcTemplate.update(sql, new Object[]{user.getName(), user.getAge(), user.getGender()}); } // 其他方法省略... } ``` 通过以上配置和使用,就能在SpringBoot项目中成功整合Druid数据并操作数据库。 ### 回答3: Spring Boot 是一个快速构建 Spring 应用程序的框架,它内置了对多种数据的支持,其中包括 Druid 数据Druid 是阿里巴巴开的一款数据库连接池和 SQL 监控工具,它可以大大提高应用程序性能和数据库安全性。在本文中,我们将学习如何使用 Spring Boot 整合 Druid 数据。 1. 引入依赖 在 pom.xml 中添加以下依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> </dependency> ``` 2. 配置数据 在 application.properties 或 application.yml 中配置 Druid 数据: ```yaml spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root # 连接池配置 spring.datasource.druid.initial-size=5 spring.datasource.druid.min-idle=5 spring.datasource.druid.max-active=20 spring.datasource.druid.max-wait=60000 spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.validation-query=SELECT 1 FROM DUAL spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false # 连接属性配置 spring.datasource.druid.filters=stat,wall spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 ``` 3. 配置 Druid 监控 可以通过以下配置开启 Druid 监控: ```yaml # 监控统计 spring.datasource.druid.stat-view-servlet.enabled=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 # 过滤器配置 spring.datasource.druid.web-stat-filter.enabled=true spring.datasource.druid.web-stat-filter.url-pattern=/* spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/* ``` 4. 使用数据 现在我们可以通过注入 DataSource 对象来使用 Druid 数据,例如: ```java @RestController public class TestController { @Autowired private DataSource dataSource; // ... } ``` 以上就是使用 Spring Boot 整合 Druid 数据的步骤。通过使用 Druid 数据可以提高应用程序的性能和数据库安全性,而 Spring Boot 可以简化整个开发过程,让开发者更加专注于业务逻辑的实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值