SpringBoot2.x 整合Druid数据源(详解及配置配置)

https://blog.csdn.net/weixin_42040802/article/details/84284183

一、我们先说启动SpringBoot2.x的默认数据源

首先正常新建一个springBoot2.x项目,引入web依赖

下面是h2数据库为例,在Maven中加入依赖

	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- h2数据库的依赖 -->
         <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

这里引入了JPA的依赖,对JPA来说,在SpringBoot中是依赖Hibernate去实现的,因此我们可以看到,在Maven依赖包下存在很多与Hibernate相关的jar,如图所示:
jpa
这样我们就可以在不需要任何配置数据库的情况下运行SpringBoot了,因为h2是内嵌式数据库,当然我们也可以将数据源配置为hqldb或者Derby。它会随着SpringBoot项目的启动而启动,当然这不是我们想要的,更多时候我们需要的商用数据库例如:MysqlOracle。因为。下面我为大家介绍如何配置其他数据库厂商的数据源。

二、 配置自定义数据源——Druid

下面以Mysql为例:首先删去对h2的依赖,增加对mysql以及Druid的依赖。

	<!--<dependency>-->
            <!--<groupId>com.h2database</groupId>-->
            <!--<artifactId>h2</artifactId>-->
            <!--<scope>runtime</scope>-->
        <!--</dependency>-->
    &lt;dependency&gt;
        &lt;groupId&gt;mysql&lt;/groupId&gt;
        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
    &lt;/dependency&gt;
    
    &lt;dependency&gt;
        &lt;groupId&gt;com.alibaba&lt;/groupId&gt;
        &lt;artifactId&gt;druid&lt;/artifactId&gt;
        &lt;version&gt;1.1.6&lt;/version&gt;
    &lt;/dependency&gt;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

这显然还不足以连接我们的数据库,还需要配置数据库相关信息才能连接到数据库,springboot中可以配置application.yml配置文件已达到配饰数据源的效果。

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/book?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
    password: ***
    username: ***
    driver-class-name: com.mysql.jdbc.Driver
    platform: mysql
    # 下面为连接池的补充设置,应用到上面所有数据源中
    type: com.alibaba.druid.pool.DruidDataSource
# 初始化大小,最小,最大
initialSize: 1
minIdle: 3
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 30000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#useGlobalDataSourceStat: true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

type: com.alibaba.druid.pool.DruidDataSource
通过这句配置将druid连接池引入到我们的配置中,spring会尽可能判断类型是什么,然后根据情况去匹配驱动类。

三、让SpringBoot的IOC容器看到我们的Druid

光有配置还不可以啊,就像你只有钱,但是花不出去它仅仅是一张纸,我们必须得让ioc看到我们的努力,所以我们自己写一个配置类。

@Configuration
public class DruidConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDataSource(){
        return new DruidDataSource();
    }
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

注意

注意DataSource 的导包

 
 
  • 1

我们可以通过一个个@value注解让每个属性都可以根据配置文件赋值,再将属性都装配到datasource中,可是那样太麻烦了,SpringBoot为我们提供了:

@ConfigurationProperties(prefix = “spring.datasource”)
通过这个注解我们可以将配置文件中的值一股脑的给这个方法,让它自动装配。

四、监控——druid可以帮我们实现监控

(也可以用作测试druid是否好用)
两个类一个是监控,一个是过滤,我们都可以进行相应的设置:

/**
 * druid数据源状态监控.
 * @author syrain
 */
@WebServlet(urlPatterns="/druid/*",
        initParams={
                @WebInitParam(name="allow",value=""),// IP白名单(没有配置或者为空,则允许所有访问)
                @WebInitParam(name="deny",value=""),// IP黑名单 (存在共同时,deny优先于allow)
                @WebInitParam(name="loginUsername",value="admin"),// 用户名
                @WebInitParam(name="loginPassword",value="admin"),// 密码
                @WebInitParam(name="resetEnable",value="true")// 禁用HTML页面上的“Reset All”功能
        }
)
public class DruidStatViewServlet  extends StatViewServlet {
    private static final long serialVersionUID = 1L;
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
/**
 * druid过滤器.
 */
@WebFilter(filterName="druidWebStatFilter",
        urlPatterns="/*",
        initParams={
                @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源
        }
)
public class DruidStatFilter  extends WebStatFilter {
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

有一点启动类一定要加上这个注解:@ServletComponentScan
在这里插入图片

五、结果

到这里druid就配置好啦,测试一下吧,启动项目
打开网址:
http://localhost:8080/druid/login.html

出现:
就说明配置成功啦!输入我们自己设置的账号密码。

在这里就可以监控我们的项目了。

六、有了数据源就需要用到我们的持久层框架了

其实SpringBoot自带了JPA(Hibernate),但是目前应用不多。
应该说目前java持久层最为主流的技术已经是MyBatis,他比其他框架更为简单易用。
紧接着SpringBoot整合MyBatis完整版请看我的另一篇博客。

    点击:↓

 
 
  • 1

SpringBoot 2.x 被 Mybatis整合

                                </div>
            <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-b6c3c6d139.css" rel="stylesheet">
                                            <div class="more-toolbox">
            <div class="left-toolbox">
                <ul class="toolbox-list">
                    
                    <li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
                        <use xlink:href="#csdnc-thumbsup"></use>
                    </svg><span class="name">点赞</span>
                    <span class="count">3</span>
                    </a></li>
                    <li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;popu_824&quot;}"><svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-csdnc-Collection-G"></use>
                    </svg><span class="name">收藏</span></a></li>
                    <li class="tool-item tool-active is-share"><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;1582594662_002&quot;}"><svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-csdnc-fenxiang"></use>
                    </svg>分享</a></li>
                    <!--打赏开始-->
                                            <!--打赏结束-->
                                            <li class="tool-item tool-more">
                        <a>
                        <svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
                        </a>
                        <ul class="more-box">
                            <li class="item"><a class="article-report">文章举报</a></li>
                        </ul>
                    </li>
                                        </ul>
            </div>
                        </div>
        <div class="person-messagebox">
            <div class="left-message"><a href="https://blog.csdn.net/weixin_42040802">
                <img src="https://profile.csdnimg.cn/D/9/C/3_weixin_42040802" class="avatar_pic" username="weixin_42040802">
                                        <img src="https://g.csdnimg.cn/static/user-reg-year/1x/2.png" class="user-years">
                                </a></div>
            <div class="middle-message">
                                    <div class="title"><span class="tit"><a href="https://blog.csdn.net/weixin_42040802" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}" target="_blank">syrain丶华思雨</a></span>
                                        </div>
                <div class="text"><span>发布了11 篇原创文章</span> · <span>获赞 20</span> · <span>访问量 1万+</span></div>
            </div>
                            <div class="right-message">
                                        <a href="https://im.csdn.net/im/main.html?userName=weixin_42040802" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
                    </a>
                                                        <a class="btn btn-sm  bt-button personal-watch" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}">关注</a>
                                </div>
                        </div>
                </div>
</article>
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello_world!

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值