Spring Boot 整合阿里巴巴的Druid(德鲁伊)数据源教程。

前詹:数据源的集中比较

目前常用的数据源主要有c3p0、dbcp、proxool、druid,先来说说他们
Spring 推荐使用dbcp;
Hibernate 推荐使用c3p0和proxool
1:BCP:apache
DBCP(DataBase connection pool)数据库连接池。是apache上的一个 java连接池项目,也是 tomcat使用的连接池组件。单独使用dbcp需要3个包:common-dbcp.jar,common-pool.jar,common-collections.jar由于建立数据库连接是一个非常耗时耗资源的行为,所以通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,用完后再放回去。dbcp没有自动的去回收空闲连接的功能。

2: C3P0:
C3P0是一个开源的jdbc连接池,它实现了数据源和jndi绑定,支持jdbc3规范和jdbc2的标准扩展。c3p0是异步操作的,缓慢的jdbc操作通过帮助进程完成。扩展这些操作可以有效的提升性能。目前使用它的开源项目有Hibernate,Spring等。c3p0有自动回收空闲连接功能。

3: Proxool:Sourceforge
Proxool是一种Java数据库连接池技术。是sourceforge下的一个开源项目,这个项目提供一个健壮、易用的连接池,最为关键的是这个连接池提供监控的功能,方便易用,便于发现连接泄漏的情况。
综合来说,稳定性是dbcp >= c3p0 > proxool

后来阿里巴巴的druid开源了,可以是前无古人后无来者,最强没有之一,十分稳定,在大并发中表现十分好,德鲁伊提供的这个监控组件,非常的便利,所有sql的监控,运行效率等等都能看到。

 

第一步:创建springboot项目的时候勾选

Web --  Spring Web, SQL-- JDBC API  ,  SQL -- MySQL Driver 这三个选项

 

第二步:添加相关pom依赖

        <!--引入Druid数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.18</version>
        </dependency>
        <!--导入配置文件处理器,配置文件进行绑定就会有提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

第三步:单独拎出druid 的 datasource 数据源配置

datasource.yml 配置文件内容:

spring:
  datasource:
    username: root
    password: sgl520
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/sgl_db
    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,wall
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

第四步:自定义druid 的 DataSource 组件 添加进容器

DruidConfig.java的代码内容:

/**
 *@ClassName DruidConfig
 *@Description TODO 数据源Druid 配置化类
 *@Author Ni Klaus
 *@Date 2019/10/8 0008 下午 17:08
 *@Version 1.0
 */

/*** 应为我们是读取单独配置的datasource.yml 数据源配置文件 所以需要指定去 classpath:datasource.yml
文件里面找 prefix = "spring.datasource" 再绑定到 DruidDataSource的属性上去
而 @PropertySource 注解 又不支持 读取.yml类型的配置文件,所以我这里自定义了一个 YamlPropertySourceFactory
类,去让 @PropertySource 注解 可以识别 .yml类型的配置文件
具体实现可以看我的另一篇博客:https://blog.csdn.net/sgl520lxl/article/details/102139764
里面的(拓展:) 部分是怎么实现的。*/
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:datasource.yml")
@Configuration
public class DruidConfig {

    //根据配置文件绑定属性,生成 DruidDataSource 组件 注入到ioc容器
    @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");//druid 后台登录名
        initParams.put("loginPassword","123456");//druid 后台登录密码
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","192.168.15.21");//拒绝的ip

        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<>();
        //放行静态文件和druid
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return  bean;
    }
}

YamlPropertySourceFactory.java 的代码内容:

/**
 *@ClassName YamlPropertySourceFactory
 *@Description TODO  重写 PropertySourceFactory 的 createPropertySource 使 @PropertySource 注解支持读取 .yml类型的配置文件
 *@Author Ni Klaus
 *@Date 2019/10/8 0008 下午 17:53
 *@Version 1.0
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

第五步:启动项目访问druid的后台地址

http://127.0.0.1:8080/druid

使用上面代码里面配置的账号密码登录

initParams.put("loginUsername","admin");//druid 后台登录名
initParams.put("loginPassword","123456");//druid 后台登录密码

就可以看到druid的视图页面了!

 

本教程项目demo源码地址:https://github.com/Hak-L/sping-boot-with-druid

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章