美文网首页程序员
(3) spring-boot+druid+mybatis环境搭

(3) spring-boot+druid+mybatis环境搭

作者: 桥头放牛娃 | 来源:发表于2018-10-30 14:58 被阅读205次

    本文以druid数据库连接池及mybatis框架,搭建基本的应用开发框架。

    1、druid数据库连接池

    1.1、Druid是什么?有什么作用?

    Druid首先是一个数据库连接池,但它不仅仅是一个数据库连接池,它还包含一个ProxyDriver,一系列内置的JDBC组件库,一个SQL Parser。

    整个项目由数据库连接池、插件框架和SQL解析器组成。该项目主要是为了扩展JDBC的一些限制,可以让程序员实现一些特殊的需求,比如向密钥服务请求凭证、统计SQL信息、SQL性能收集、SQL注入检查、SQL翻译等,程序员可以通过定制来实现自己需要的功能。
    github:https://github.com/alibaba/druid

    1.2、Druid支持哪些数据库?

    Druid支持所有JDBC兼容的数据库,包括Oracle、MySql、Derby、Postgresql、SQL Server、H2等等。
    Druid针对Oracle和MySql做了特别优化,比如Oracle的PS Cache内存占用优化,MySql的ping检测优化。

    1.3、Druid是如何扩展JDBC的?

    Druid在DruidDataSourc和ProxyDriver上提供了Filter-Chain模式的扩展API,类似Serlvet的Filter,配置Filter拦截JDBC的方法调用。

    1.4、Druid有那些监控特性?

    • 监控SQL的执行时间、ResultSet持有时间、返回行数、更新行数、错误次数、错误堆栈信息。
    • SQL执行的耗时区间分布。什么是耗时区间分布呢?比如说,某个SQL执行了1000次,其中01毫秒区间50次,110毫秒800次,10100毫秒100次,1001000毫秒30次,1~10秒15次,10秒以上5次。通过耗时区间分布,能够非常清楚知道SQL的执行耗时情况。
    • 监控连接池的物理连接创建和销毁次数、逻辑连接的申请和关闭次数、非空等待次数、PSCache命中率等。

    2、配置druid数据库连接池

    目前Spring Boot中默认支持的连接池有dbcp,dbcp2, tomcat, hikari三种连接池,若要支持druid,需要我们自己配置;

    2.1、基于java代码配置

    2.1.1、pom依赖

    <dependency>
    
      <groupId>mysql</groupId>
    
      <artifactId>mysql-connector-java</artifactId>
    
      <scope>runtime</scope>
    
    </dependency>
    
    <dependency>
    
      <groupId>com.alibaba</groupId>
    
      <artifactId>druid</artifactId>
    
      <version>1.0.25</version>
    
    </dependency>
    

    2.1.2、application.properties配置信息

    # 驱动配置信息
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.datasource.url = jdbc:mysql://192.168.101.xx:3306/jdronetest?characterEncoding=UTF-8
    spring.datasource.username = xxxxx
    spring.datasource.password = xxxxxxx
    
    #连接池的配置信息
    spring.datasource.initialSize=2
    spring.datasource.minIdle=2
    spring.datasource.maxActive=2
    spring.datasource.maxWait=60000
    spring.datasource.timeBetweenEvictionRunsMillis=60000
    spring.datasource.minEvictableIdleTimeMillis=300000
    spring.datasource.validationQuery=SELECT 1 FROM USER
    spring.datasource.testWhileIdle=true
    spring.datasource.testOnBorrow=false
    spring.datasource.testOnReturn=false
    spring.datasource.poolPreparedStatements=true
    spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
    spring.datasource.filters=stat,wall,log4j
    spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    

    2.1.3、定义DataSource

    package com.springboot.demo.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    
    import javax.sql.DataSource;
    import java.sql.SQLException;
    
    @SuppressWarnings("all")
    @Configuration
    public class DruidConfig {
        private static final Logger log = LoggerFactory.getLogger(DruidConfig.class);
    
        @Value("${spring.datasource.url}")
        private String dbUrl;
    
        @Value("${spring.datasource.username}")
        private String username;
    
        @Value("${spring.datasource.password}")
        private String password;
    
        @Value("${spring.datasource.driverClassName}")
        private String driverClassName;
    
        @Value("${spring.datasource.initialSize}")
        private int initialSize;
    
        @Value("${spring.datasource.minIdle}")
        private int minIdle;
    
        @Value("${spring.datasource.maxActive}")
        private int maxActive;
    
        @Value("${spring.datasource.maxWait}")
        private int maxWait;
    
        @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
        private int timeBetweenEvictionRunsMillis;
    
        @Value("${spring.datasource.minEvictableIdleTimeMillis}")
        private int minEvictableIdleTimeMillis;
    
        @Value("${spring.datasource.validationQuery}")
        private String validationQuery;
    
        @Value("${spring.datasource.testWhileIdle}")
        private boolean testWhileIdle;
    
        @Value("${spring.datasource.testOnBorrow}")
        private boolean testOnBorrow;
    
        @Value("${spring.datasource.testOnReturn}")
        private boolean testOnReturn;
    
        @Value("${spring.datasource.poolPreparedStatements}")
        private boolean poolPreparedStatements;
    
        @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
        private int maxPoolPreparedStatementPerConnectionSize;
    
        @Value("${spring.datasource.filters}")
        private String filters;
    
        @Value("{spring.datasource.connectionProperties}")
        private String connectionProperties;
    
        @Bean(initMethod = "init", destroyMethod = "close")
        @Primary
        public DataSource dataSource() {
            DruidDataSource datasource = new DruidDataSource();
    
            datasource.setUrl(this.dbUrl);
            datasource.setUsername(username);
            datasource.setPassword(password);
            datasource.setDriverClassName(driverClassName);
    
            /** configuration */
            datasource.setInitialSize(initialSize);
            datasource.setMinIdle(minIdle);
            datasource.setMaxActive(maxActive);
            datasource.setMaxWait(maxWait);
            datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
            datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
            datasource.setValidationQuery(validationQuery);
            datasource.setTestWhileIdle(testWhileIdle);
            datasource.setTestOnBorrow(testOnBorrow);
            datasource.setTestOnReturn(testOnReturn);
            datasource.setPoolPreparedStatements(poolPreparedStatements);
            datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
            try {
                datasource.setFilters(filters);
            } catch (SQLException e) {
                log.error("druid configuration initialization filter", e);
            }
            datasource.setConnectionProperties(connectionProperties);
            return datasource;
        }
    
        /**
         * http://127.0.0.1:8090/monitor/druid/login.html
         *
         * @throws
         * @Title: druidServlet
         * @Description: 注册一个StatViewServlet 相当于在web.xml中声明了一个servlet
         * @param: void
         * @return: ServletRegistrationBean
         */
        @Bean
        public ServletRegistrationBean druidServlet() {
            ServletRegistrationBean reg = new ServletRegistrationBean();
            reg.setServlet(new StatViewServlet());
            reg.addUrlMappings("/druid/*");
            /** 白名单 */
            // IP白名单
            reg.addInitParameter("allow", "*");
            // IP黑名单(共同存在时,deny优先于allow)
            reg.addInitParameter("deny", "192.168.1.100");
    
            /** /druid/login.html登录时账号密码 */
            reg.addInitParameter("loginUsername", "zhaozhou");
            reg.addInitParameter("loginPassword", "zhaozhou");
            /** 是否能够重置数据 禁用HTML页面上的“Reset All”功能 */
            reg.addInitParameter("resetEnable", "false");
            return reg;
        }
    
        /**
         * 注册一个:filterRegistrationBean 相当于在web.xml中声明了一个Filter
         */
        @Bean
        public FilterRegistrationBean druidStatFilter() {
            FilterRegistrationBean druidStatFilter = new FilterRegistrationBean();
            druidStatFilter.setFilter(new WebStatFilter());
            /** 添加过滤规则. */
            druidStatFilter.addUrlPatterns("/*");
            /** 监控选项滤器 */
            druidStatFilter.addInitParameter("DruidWebStatFilter", "/*");
            /** 添加不需要忽略的格式信息. */
            druidStatFilter.addInitParameter("exclusions",
                    "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
            /** 配置profileEnable能够监控单个url调用的sql列表 */
            druidStatFilter.addInitParameter("profileEnable", "true");
            /** 当前的cookie的用户 */
            druidStatFilter.addInitParameter("principalCookieName", "USER_COOKIE");
            /** 当前的session的用户 */
            druidStatFilter
                    .addInitParameter("principalSessionName", "USER_SESSION");
            return druidStatFilter;
        }
    }
    
    

    2.2、基于starter配置

    此种配置只需要配置pom及application.properties信息即可;

    2.2.1、pom配置

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.8</version>
    </dependency>
    

    2.3、mybatis配置

    2.3.1、pom配置

    <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
    </dependency>
    

    2.3.2、application.properties配置

    mybatis.mapper-locations=classpath:mapper/*.xml
    mybatis.type-aliases-package=com.springboot.demo.entity
    

    2.3.3、@MapperScan配置

    @SpringBootApplication
    @MapperScan("com.springboot.demo.dao")
    public class TestApplication {
    
      public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
      }
    }
    

    2.3.3、mabatis扩展配置

    mybatis.config-location:指定mybatis-config.xml的位置;
    mybatis.check-config-location:检查mybatis-config.xml是否存在;
    mybatis.mapper-locations:指定mapper的xml的位置;
    mybatis.type-aliases-package:指定别名的包,可以多个,逗号分隔;
    mybatis.type-handlers-package:指定handler的扫描码路径;
    mybatis.executor-type:执行器类型: SIMPLE, REUSE, BATCH;
    mybatis.configuration-properties:MyBatis配置的外部化属性。指定的属性可以用作MyBatis配置文件和映射文件的占位符;
    mybatis.configuration:嵌套配置,具体子配置如下;
    defaultStatementTimeout:设置超时时间,它决定驱动等待数据库响应的秒数;
    defaultFetchSize:为驱动的结果集获取数量(fetchSize)设置一个提示值。此参数只可以在查询设置中被覆盖;
    mapUnderscoreToCamelCase:是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射;
    autoMappingUnknownColumnBehavior:指定发现自动映射目标未知列(或者未知属性类型)的行为;NONE:不做任何反应;WARNING:输出提醒日志 ('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' 的日志等级必须设置为 WARN);FAILING:映射失败 (抛出 SqlSessionException);

    具体参考:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

    2.3、日志配置

    2.3.1、pom配置

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    

    2.3.2、application.properties配置

    logging.level.root = debug
    

    本处只做基本的root配置,可以看到sql的日志即可,不做过多配置;

    3、项目最终结果

    3.1、项目目录结构

    目录结构.png

    3.2、dao层

    package com.springboot.demo.dao;
    
    import com.springboot.demo.entity.User;
    
    public interface UserDao {
        User getUserById(Long id);
    
    }
    

    dao层只提供一个接口,通过用户id查找用户信息;

    3.3、entity数据库实体

    /**
     * @author 
     */
    public class User implements Serializable {
        /**
         * 主键id
         */
        private Long id;
    
        /**
         * 用户名
         */
        private String name;
    
        /**
         * 电话
         */
        private String tel;
        /**
         * 邮件
         */
        private String email;
    
        /**
         * 航线编号
         */
        private Date createTime;
    
        //getter、setter方法
    }
    

    3.4、mapper文件

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.springboot.demo.dao.UserDao">
      <resultMap id="BaseResultMap" type="com.springboot.demo.entity.User">
        <id column="id" jdbcType="BIGINT" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="tel" jdbcType="VARCHAR" property="tel"/>
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
      </resultMap>
    
      <sql id="Base_Column_List">
        id, name, tel, email, create_time
      </sql>
    
    
    <!--  通过ID获取用户信息-->
      <select id="getUserById" parameterType="Long" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from t_user
        <where>
          id = #{id, jdbcType=BIGINT}
        </where>
      </select>
    </mapper>
    

    3.5、test测试用例

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class TestApplicationTests {
    
        @Resource
        private UserService userService;
    
        @Test
        public void getUserTest() {
            User user = userService.getUserById(1L);
            System.out.println("用户名:" + user.getName());
        }
    
    }
    

    3.6、运行test结果

    2018-10-30 14:57:14.552 DEBUG 9816 --- [           main] org.mybatis.spring.SqlSessionUtils       : Creating a new SqlSession
    2018-10-30 14:57:14.556 DEBUG 9816 --- [           main] org.mybatis.spring.SqlSessionUtils       : SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f1fb828] was not registered for synchronization because synchronization is not active
    2018-10-30 14:57:14.595 DEBUG 9816 --- [           main] o.s.jdbc.datasource.DataSourceUtils      : Fetching JDBC Connection from DataSource
    2018-10-30 14:57:14.599 DEBUG 9816 --- [           main] o.m.s.t.SpringManagedTransaction         : JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@6a55594b] will not be managed by Spring
    2018-10-30 14:57:14.603 DEBUG 9816 --- [           main] c.s.demo.dao.UserDao.getUserById         : ==>  Preparing: select id, name, tel, email, create_time from t_user WHERE id = ? 
    2018-10-30 14:57:14.769 DEBUG 9816 --- [           main] c.s.demo.dao.UserDao.getUserById         : ==> Parameters: 1(Long)
    2018-10-30 14:57:14.790 DEBUG 9816 --- [           main] c.s.demo.dao.UserDao.getUserById         : <==      Total: 1
    2018-10-30 14:57:14.791 DEBUG 9816 --- [           main] c.a.druid.pool.PreparedStatementPool     : {conn-10002, pstmt-20000} enter cache
    2018-10-30 14:57:14.791 DEBUG 9816 --- [           main] org.mybatis.spring.SqlSessionUtils       : Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f1fb828]
    2018-10-30 14:57:14.791 DEBUG 9816 --- [           main] o.s.jdbc.datasource.DataSourceUtils      : Returning JDBC Connection to DataSource
    用户名:zhaozhou
    

    以上为运行查询日志,可以看到,数据库事务及查询语句都运行正常。

    示例源码:https://github.com/zhaozhou11/spring-boot-demo.git

    相关阅读:
    spring-boot基础环境搭建 【https://www.jianshu.com/p/ee36bb9faa10
    spring-boot配置详解【https://www.jianshu.com/p/1d037ab638ef
    spring-boot+logback+log4j2+MDC【https://www.jianshu.com/p/51da61a425ba

    参考博客:
    https://blog.csdn.net/moshowgame/article/details/80304198
    https://blog.csdn.net/zjh_746140129/article/details/81254987
    https://blog.csdn.net/m0_38044453/article/details/81132523

    相关文章

      网友评论

        本文标题:(3) spring-boot+druid+mybatis环境搭

        本文链接:https://www.haomeiwen.com/subject/jouitqtx.html