【Java】Springboot集成Druid

Springboot集成Druid方案:一个是在POM中直接配置druid-spring-boot-starter,不用写任何代码;一个是配置druid,写几行代码,可以加入;在方案一基础上加入stat、wall后进行验证登录。

测试环境是:SpringBoot2.1.4.RELEASE。

一、直接使用druid-spring-boot-starter

1、POM配置

复制代码
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--自启动Druid管理后台-->
                <dependency>
                    <groupId>com.alibaba</groupId>
                    <artifactId>druid-spring-boot-starter</artifactId>
                    <version>1.1.10</version>
                </dependency>
复制代码

2、application.properties配置

复制代码
### db config ###
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/XXX?useUnicode=true&characterEncoding=utf8&currentSchema=public
spring.datasource.username=postgres
spring.datasource.password=XXX
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.hbm2ddl.auto=update
#config druid
#连接池的设置
#初始化时建立物理连接的个数
spring.datasource.druid.initial-size=5
#最小连接池数量
spring.datasource.druid.min-idle=5
#最大连接池数量 maxIdle已经不再使用
spring.datasource.druid.max-active=20
#获取连接时最大等待时间,单位毫秒
spring.datasource.druid.max-wait=60000
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
spring.datasource.druid.test-while-idle=true
#既作为检测的间隔时间又作为testWhileIdel执行的依据
spring.datasource.druid.time-between-eviction-runs-millis=60000
#销毁线程时检测当前连接的最后活动时间和当前时间差大于该值时,关闭当前连接
spring.datasource.druid.min-evictable-idle-time-millis=30000
#用来检测连接是否有效的sql 必须是一个查询语句
#mysql中为 select 'x'
#oracle中为 select 1 from dual
spring.datasource.druid.validation-query=select 'x'
#申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
spring.datasource.druid.test-on-borrow=false
#归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
spring.datasource.druid.test-on-return=false
#当数据库抛出不可恢复的异常时,抛弃该连接
spring.datasource.druid.exception-sorter=true
#是否缓存preparedStatement,mysql5.5+建议开启
#spring.datasource.druid.pool-prepared-statements=true
#当值大于0时poolPreparedStatements会自动修改为true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
#配置扩展插件
spring.datasource.druid.filters=stat,wall
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#合并多个DruidDataSource的监控数据
spring.datasource.druid.use-global-data-source-stat=true
#设置访问druid监控页的账号和密码,默认没有
#spring.datasource.druid.stat-view-servlet.login-username=admin
#spring.datasource.druid.stat-view-servlet.login-password=admin

### mybatis config ###
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.jrsc.supervisor.model
### log config ###
logging.config=classpath:logback-spring.xml
复制代码

3、输入http://localhost:9091/druid/webapp.html后,即可看到Druid监控面板

PS:广告无处不在

 

二、使用代码,可验证登录的方案

1、POM配置,删除:druid-spring-boot-starter

复制代码
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--自启动Druid管理后台-->
        <!--        <dependency>-->
        <!--            <groupId>com.alibaba</groupId>-->
        <!--            <artifactId>druid-spring-boot-starter</artifactId>-->
        <!--            <version>1.1.10</version>-->
        <!--        </dependency>-->
复制代码

2、application.properties配置不变

3、新建一个类:DruidConfig,注意包的引入,特别是:

复制代码
package com.jrsc.supervisor.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 javax.sql.DataSource;
复制代码

3、DruidConfig具体实现如下:

复制代码
@Configuration
public class DruidConfig {

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

    @Bean
    public ServletRegistrationBean druidStatViewServlet() {
        //ServletRegistrationBean提供类的进行注册
        ServletRegistrationBean servletRegistrationBean =
                new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //添加初始化参数:initParams
        //白名单:
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        //IP黑名单(同时存在时,deny优先于allow)
        //如果满足deny,就提示:sorry,you are not permitted to view this page
        servletRegistrationBean.addInitParameter("deny", "192.168.1.73");
        //登录查看信息的账号和密码
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }


    @Bean
    public FilterRegistrationBean druidStatFilter() {
        FilterRegistrationBean filterRegistrationBean =
                new FilterRegistrationBean(new WebStatFilter());
        //添加过滤规则
        filterRegistrationBean.addUrlPatterns("/*");
        //添加需要忽略的格式信息
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif," +
                "*.jpg,*.png, *.css,*.ico,/druid/*");
        return filterRegistrationBean;

    }
复制代码

4、对于SpringBoot的启动类,加入注解:@ServletComponentScan

5、输入:http://localhost:9091/druid/sql.html,观察Druid监控面板

三、通过在方案一基础上加入如下代码,实现验证登录

复制代码
#设置访问druid监控页的账号和密码,默认没有
## Druid WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.gif,*.png,*.jpg,*.html,*.js,*.css,*.ico,/druid/*
# Druid StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=123456
spring.datasource.druid.stat-view-servlet.allow=
spring.datasource.druid.stat-view-servlet.deny=

VMware虚拟机中Centos 6.x系统磁盘空间扩容实战

环境:
CentOS 6.9

平常在VMware上创建Linux系统虚拟机的时候,往往当时不会给太多的磁盘空间,在后期的使用过程中经常会遇到磁盘空间不足的情况,所以需要对Linux系统扩展磁盘空间。

扩展磁盘步骤:
1.磁盘扩展

注意:只能在虚拟机关机的情况下操作,并且这个虚拟机上没有磁盘快照文件,如有需要删除才可以扩展。

此时虽然在VMware虚拟机管理界面的扩容操作已经完成,但是这还只是扩容的第一步,后面还需要到操作系统内部进行操作。

2.查看分区信息

[root@test-centos6 ~]# fdisk -l

Disk /dev/sda: 64.4 GB, 64424509440 bytes
255 heads, 63 sectors/track, 7832 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000a16bc

Device Boot Start End Blocks Id System
/dev/sda1 * 1 64 512000 83 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 64 2611 20458496 8e Linux LVM

Disk /dev/mapper/vg_testcentos6-lv_root: 18.8 GB, 18798870528 bytes
255 heads, 63 sectors/track, 2285 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/vg_testcentos6-lv_swap: 2147 MB, 2147483648 bytes
255 heads, 63 sectors/track, 261 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

[root@test-centos6 ~]# lsblk //列出块设备信息
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sr0 11:0 1 447M 0 rom
sda 8:0 0 60G 0 disk
├─sda1 8:1 0 500M 0 part /boot
└─sda2 8:2 0 19.5G 0 part
├─vg_testcentos6-lv_root (dm-0) 253:0 0 17.5G 0 lvm /
└─vg_testcentos6-lv_swap (dm-1) 253:1 0 2G 0 lvm [SWAP]

可以看到目前磁盘/dev/sda已经有两个分区,分别为sda1、sda2。

3.新建分区sda3

[root@test-centos6 ~]# fdisk /dev/sda

WARNING: DOS-compatible mode is deprecated. It’s strongly recommended to
switch off the mode (command ‘c’) and change display units to
sectors (command ‘u’).

Command (m for help): m //列出可以执行的命令
Command action
a toggle a bootable flag
b edit bsd disklabel
c toggle the dos compatibility flag
d delete a partition
l list known partition types
m print this menu
n add a new partition //选择分区,删除现有分区
o create a new empty DOS partition table
p print the partition table
q quit without saving changes
s create a new empty Sun disklabel
t change a partition’s system id
u change display/entry units
v verify the partition table
w write table to disk and exit
x extra functionality (experts only)

Command (m for help): n //建立新的磁盘分区
Command action
e extended //逻辑分区
p primary partition (1-4) //主分区
p //建立主分区
Partition number (1-4): 3 //输入分区号
First cylinder (2611-7832, default 2611): //分区起始位置(可直接回车也可以根据情况输入)
Using default value 2611
Last cylinder, +cylinders or +size{K,M,G} (2611-7832, default 7832): //回车
Using default value 7832

Command (m for help): p //列出磁盘目前的分区情况

Disk /dev/sda: 64.4 GB, 64424509440 bytes
255 heads, 63 sectors/track, 7832 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000a16bc

Device Boot Start End Blocks Id System
/dev/sda1 * 1 64 512000 83 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 64 2611 20458496 8e Linux LVM
/dev/sda3 2611 7832 41939020 83 Linux

Command (m for help): w //对分区操作进行保存
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: 设备或资源忙.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks. //正在同步磁盘

[root@test-centos6 ~]# fdisk -l //查看分区创建情况

Disk /dev/sda: 64.4 GB, 64424509440 bytes
255 heads, 63 sectors/track, 7832 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000a16bc

Device Boot Start End Blocks Id System
/dev/sda1 * 1 64 512000 83 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 64 2611 20458496 8e Linux LVM
/dev/sda3 2611 7832 41939020 83 Linux

Disk /dev/mapper/vg_testcentos6-lv_root: 18.8 GB, 18798870528 bytes
255 heads, 63 sectors/track, 2285 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/vg_testcentos6-lv_swap: 2147 MB, 2147483648 bytes
255 heads, 63 sectors/track, 261 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

4.重启系统并格式化分区sda3文件系统

[root@test-centos6 ~]# reboot

[root@test-centos6 ~]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sr0 11:0 1 447M 0 rom
sda 8:0 0 60G 0 disk
├─sda1 8:1 0 500M 0 part /boot
├─sda2 8:2 0 19.5G 0 part
│ ├─vg_testcentos6-lv_root (dm-0) 253:0 0 17.5G 0 lvm /
│ └─vg_testcentos6-lv_swap (dm-1) 253:1 0 2G 0 lvm [SWAP]
└─sda3 8:3 0 40G 0 part

[root@test-centos6 ~]# mkfs.ext4 /dev/sda3 //将/dev/sda3分区文件系统格式化为ext4
mke2fs 1.41.12 (17-May-2010)
文件系统标签=
操作系统:Linux
块大小=4096 (log=2)
分块大小=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
2621440 inodes, 10484755 blocks
524237 blocks (5.00%) reserved for the super user
第一个数据块=0
Maximum filesystem blocks=4294967296
320 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
4096000, 7962624

正在写入inode表: 完成
Creating journal (32768 blocks): 完成
Writing superblocks and filesystem accounting information: 完成

This filesystem will be automatically checked every 35 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.

5.创建物理卷(pv)

此步骤可省略:当将分区直接添加到卷组(vg)时,LVM会自动将分区转换为物理卷(pv)。

[root@test-centos6 ~]# lvm
lvm> pvcreate /dev/sda3 //创建物理卷pv
Physical volume “/dev/sda3” successfully created
lvm> pvdisplay //显示物理卷pv信息
— Physical volume —
PV Name /dev/sda2
VG Name vg_testcentos6
PV Size 19.51 GiB / not usable 3.00 MiB
Allocatable yes (but full)
PE Size 4.00 MiB
Total PE 4994
Free PE 0
Allocated PE 4994
PV UUID jMIPOc-sduo-sl4T-6iQ5-ledQ-1w9O-cweeEC

“/dev/sda3” is a new physical volume of “40.00 GiB”
— NEW Physical volume —
PV Name /dev/sda3
VG Name
PV Size 40.00 GiB
Allocatable NO
PE Size 0
Total PE 0
Free PE 0
Allocated PE 0
PV UUID PVrdc7-fUEX-PAxZ-ME92-IuNU-khDC-c5tYlp

lvm> pvdisplay
— Physical volume —
PV Name /dev/sda2
VG Name vg_testcentos6
PV Size 19.51 GiB / not usable 3.00 MiB
Allocatable yes (but full)
PE Size 4.00 MiB
Total PE 4994
Free PE 0
Allocated PE 4994
PV UUID jMIPOc-sduo-sl4T-6iQ5-ledQ-1w9O-cweeEC

“/dev/sda3” is a new physical volume of “40.00 GiB”
— NEW Physical volume —
PV Name /dev/sda3
VG Name
PV Size 40.00 GiB
Allocatable NO
PE Size 0
Total PE 0
Free PE 0
Allocated PE 0
PV UUID PVrdc7-fUEX-PAxZ-ME92-IuNU-khDC-c5tYlp

6.查看并创建卷组(vg)

lvm> vgdisplay //查看需要扩展的卷组vg名称
— Volume group —
VG Name vg_testcentos6 //卷组vg名称
System ID
Format lvm2
Metadata Areas 3
Metadata Sequence No 6
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 2
Open LV 2
Max PV 0
Cur PV 3
Act PV 3
VG Size 59.49 GiB
PE Size 4.00 MiB
Total PE 17790
Alloc PE / Size 15232 / 19.50 GiB
Free PE / Size 2558 / 9.99 GiB
VG UUID yVVWYi-mV3I-f1WI-2QeH-HkVT-oBXP-2KkQ8v

lvm> vgextend vg_testcentos6 /dev/sda3 //扩展卷组(这里的“vg_testcentos6”名称为上面的卷组名称)
Volume group “vg_testcentos6” successfully extended

7.扩展逻辑卷(lv)

[root@test-centos6 ~]# df -h //查看扩展路径,这里也可以用fdisk -l查看
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/vg_testcentos6-lv_root —–》 //**扩展路径**
18G 18G 0 100% /
tmpfs 1.9G 0 1.9G 0% /dev/shm
/dev/sda1 485M 58M 403M 13% /boot

[root@test-centos6 ~]# lvm //进入LVM管理器

lvm> lvextend -L +39.99G /dev/mapper/vg_testcentos6-lv_root //扩展逻辑卷lv大小(通过fdisk -l/df -h查看要扩展过去的磁盘)
Rounding size to boundary between physical extents: 39.99 GiB.
Size of logical volume vg_testcentos6/lv_root changed from 17.51 GiB (4482 extents) to 57.50 GiB (14720 extents)
Logical volume lv_root successfully resized.

lvm> lvscan
ACTIVE ‘/dev/vg_testcentos6/lv_root’ [57.50 GiB] inherit
ACTIVE ‘/dev/vg_testcentos6/lv_swap’ [2.00 GiB] inherit

lvm> pvscan
PV /dev/sda2 VG vg_testcentos6 lvm2 [19.51 GiB / 0 free]
PV /dev/sda3 VG vg_testcentos6 lvm2 [39.99 GiB / 0 free]
Total: 2 [59.50 GiB] / in use: 2 [59.50 GiB] / in no VG: 0 [0 ]

lvm> exit
Exiting.

8.查看分区情况

[root@test-centos6 ~]# fdisk -l

Disk /dev/sda: 64.4 GB, 64424509440 bytes
255 heads, 63 sectors/track, 7832 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000a16bc

Device Boot Start End Blocks Id System
/dev/sda1 * 1 64 512000 83 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 64 2611 20458496 8e Linux LVM
/dev/sda3 2611 7832 41939020 83 Linux

Disk /dev/mapper/vg_testcentos6-lv_root: 18.8 GB, 18798870528 bytes
255 heads, 63 sectors/track, 2285 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/vg_testcentos6-lv_swap: 2147 MB, 2147483648 bytes
255 heads, 63 sectors/track, 261 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

注意:上面虽然显示物理卷/dev/sdb3有40G空闲,但是这里不能全部使用,可能只有39.99G可以使用。

7.激活即重新读取磁盘信息

查看/dev/mapper/vg_testcentos6-lv_root的Type为ext4,所以使用resize2fs;如果文件类型是 xfs ,则使用xfs_growfs命令格式化。

[root@test-centos6 ~]# blkid //查看文件系统
/dev/sda1: UUID=”32a489a3-65c2-43a4-9aff-12c03eabc4dd” TYPE=”ext4″
/dev/sda2: UUID=”jMIPOc-sduo-sl4T-6iQ5-ledQ-1w9O-cweeEC” TYPE=”LVM2_member”
/dev/sda3: UUID=”PVrdc7-fUEX-PAxZ-ME92-IuNU-khDC-c5tYlp” TYPE=”LVM2_member”
/dev/mapper/vg_testcentos6-lv_root: UUID=”e8adf717-e78c-4845-a750-2a22a60689ed” TYPE=”ext4″ //可以看到文件系统格式化为ext4
/dev/mapper/vg_testcentos6-lv_swap: UUID=”ac33f130-95cc-4046-8bdd-db2d7c450f6d” TYPE=”swap”

[root@test-centos6 ~]# resize2fs /dev/mapper/vg_testcentos6-lv_root //ext4文件系统使用resize2fs
resize2fs 1.41.12 (17-May-2010)
Filesystem at /dev/mapper/vg_testcentos6-lv_root is mounted on /; on-line resizing required
old desc_blocks = 2, new_desc_blocks = 4
Performing an on-line resize of /dev/mapper/vg_testcentos6-lv_root to 15073280 (4k) blocks.
The filesystem on /dev/mapper/vg_testcentos6-lv_root is now 15073280 blocks long.

[root@test-centos6 ~]# df -h //查看激活状态
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/vg_testcentos6-lv_root
57G 4.4G 50G 9% /
tmpfs 1.9G 244K 1.9G 1% /dev/shm
/dev/sda1 485M 58M 403M 13% /boot

可以看到现在我们的磁盘已经从最开始的19G扩展到了57G。