springboot (12) druid

druid是阿里巴巴开源的数据库连接池,提供了优秀的对数据库操作的监控功能,本文要讲解一下springboot项目怎么集成druid。

本文在基于jpa的项目下开发,首先在pom文件中额外加入druid依赖,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.liming</groupId>
    <artifactId>springboot_druid</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>springboot_druid</name>
    <description>springboot_druid</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.28</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.properties上半段和整合jpa一点没变,下面加入了一些druid的配置,如果对druid的配置有什么不理解的,可以去网上查一下。(这篇文章我觉得写的很好,传送门)

端口号

server.port=8888

validate

加载hibernate时,验证创建数据库表结构

create

每次加载hibernate,重新创建数据库表结构,这就是导致数据库表数据丢失的原因。

create-drop

加载hibernate时创建,退出是删除表结构

update

加载hibernate自动更新数据库结构

validate

启动时验证表的结构,不会创建表

none

启动时不做任何操作
spring.jpa.hibernate.ddl-auto=create

控制台打印sql

spring.jpa.show-sql=true

数据库配置

数据库地址

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false

数据库用户名

spring.datasource.username=root

数据库密码

spring.datasource.password=root

数据库驱动

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

这里是不同的

使用druid的话 需要多配置一个属性spring.datasource.type

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource  

连接池的配置信息

初始化大小,最小,最大

spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=20  

配置获取连接等待超时的时间

spring.datasource.maxWait=60000  

配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒

spring.datasource.timeBetweenEvictionRunsMillis=60000  

配置一个连接在池中最小生存的时间,单位是毫秒

spring.datasource.minEvictableIdleTimeMillis=300000  
spring.datasource.validationQuery=SELECT 1 FROM DUAL  
spring.datasource.testWhileIdle=true  
spring.datasource.testOnBorrow=false  
spring.datasource.testOnReturn=false  

打开PSCache,并且指定每个连接上PSCache的大小

spring.datasource.poolPreparedStatements=true  
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  

配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙

spring.datasource.filters=stat,wall,log4j

通过connectProperties属性来打开mergeSql功能;慢SQL记录

然后在项目中加入DruidConfig,简单讲解一下,这个配置文件主要是加载application.properties的配置,代码如下:

   package com.liming.config;
    import java.sql.SQLException;
    import javax.sql.DataSource;
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import com.alibaba.druid.pool.DruidDataSource;
    /**
     * @author liming
     * @Description
     * @project springboot_learn
     * @package com.liming.config
     * @email 394498036@qq.cn
     * @date 2018/4/12
     */
    @Configuration
    public class DruidConfig {
        private Logger logger = Logger.getLogger(this.getClass());
        @Value("${spring.datasource.url}")
        private String dbUrl;
        @Value("${spring.datasource.username}")
        private String username;
        @Value("${spring.datasource.password}")
        private String password;
        @Value("${spring.datasource.driver-class-name}")
        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
        @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) {
                logger.error("druid configuration Exception", e);
            }
            datasource.setConnectionProperties(connectionProperties);
            return datasource;
        }
    }

然后创建DruidFilter,代码如下:

package com.liming.filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import com.alibaba.druid.support.http.WebStatFilter;
/**
 * @author liming
 * @Description
 * @project springboot_learn
 * @package com.liming.filter
 * @email 394498036@qq.cn
 * @date 2018/4/12
 */
@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
        initParams={
                @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源
        }
)
public class DruidFilter extends WebStatFilter  {
}

新建DruidServlet,在类上面加注解@WebServlet,其中配置了登录druid监控页面的账号密码,白名单黑名单之类的配置,代码如下:

package com.liming.servlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import com.alibaba.druid.support.http.StatViewServlet;
/**
 * @author liming
 * @Description
 * @project springboot_learn
 * @package com.liming.servlet
 * @email 394498036@qq.cn
 * @date 2018/4/12
 */
@WebServlet(urlPatterns="/druid/*",
        initParams={
                @WebInitParam(name="allow",value=""),// IP白名单(没有配置或者为空,则允许所有访问)
                @WebInitParam(name="deny",value=""),// IP黑名单 (deny优先于allow)
                @WebInitParam(name="loginUsername",value="admin"),// 登录druid管理页面用户名
                @WebInitParam(name="loginPassword",value="admin")// 登录druid管理页面密码
        })
public class DruidServlet extends StatViewServlet {
}

然后在启动类加入注解@ServletComponentScan,让项目扫描到servlet,代码如下:

package com.liming;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
// 启动类必须加入@ServletComponentScan注解,否则无法扫描到servlet
@ServletComponentScan
public class SpringbootDruidApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootDruidApplication.class, args);
    }
}

剩余的就是和整合jpa一样的entity(实体类),repository(数据操作层),controller(测试使用的controller),直接展示代码。

City

package com.liming.entity;
import javax.persistence.*;
/**
 * @author liming
 * @Description
 * @project springboot_learn
 * @package com.liming.Entity
 * @email 394498036@qq.com
 * @date 2018/4/7
 */
@Entity
@Table(name="city")
public class City {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int cityId;
    private String cityName;
    private String cityIntroduce;
    public City(int cityId, String cityName, String cityIntroduce) {
        this.cityId = cityId;
        this.cityName = cityName;
        this.cityIntroduce = cityIntroduce;
    }
    public City(String cityName, String cityIntroduce) {
        this.cityName = cityName;
        this.cityIntroduce = cityIntroduce;
    }
    public City() {
    }
    public int getCityId() {
        return cityId;
    }
    public void setCityId(int cityId) {
        this.cityId = cityId;
    }
    public String getCityName() {
        return cityName;
    }
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
    public String getCityIntroduce() {
        return cityIntroduce;
    }
    public void setCityIntroduce(String cityIntroduce) {
        this.cityIntroduce = cityIntroduce;
    }
}


CityRepository

package com.liming.repository;
import com.liming.entity.City;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * @author liming
 * @Description
 * @project springboot_learn
 * @package com.liming.Repository
 * @email 394498036@qq.com
 * @date 2018/4/7
 */
public interface CityRepository extends JpaRepository<City,Integer> {
}

CityController

package com.liming.controller;
import com.liming.entity.City;
import com.liming.repository.CityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author liming
 * @Description
 * @project springboot_learn
 * @package com.liming.controller
 * @email 394498036@qq.com
 * @date 2018/4/7
 */
@RestController
public class CityController {
    @Autowired
    private CityRepository cityRepository;
    //http://localhost:8888/saveCity?cityName=北京&cityIntroduce=中国首都
    @GetMapping(value = "saveCity")
    public String saveCity(String cityName,String cityIntroduce){
        City city = new City(cityName,cityIntroduce);
        cityRepository.save(city);
        return "success";
    }
    //http://localhost:8888/deleteCity?cityId=2
    @GetMapping(value = "deleteCity")
    public String deleteCity(int cityId){
        cityRepository.delete(cityId);
        return "success";
    }
    //http://localhost:8888/updateCity?cityId=3&cityName=沈阳&cityIntroduce=辽宁省省会
    @GetMapping(value = "updateCity")
    public String updateCity(int cityId,String cityName,String cityIntroduce){
        City city = new City(cityId,cityName,cityIntroduce);
        cityRepository.save(city);
        return "success";
    }
    //http://localhost:8888/getCityById?cityId=3
    @GetMapping(value = "getCityById")
    public City getCityById(int cityId){
        City city = cityRepository.findOne(cityId);
        return city;
    }
}

然后启动项目,可以看到控制台已经创建了city表。

然后访问http://localhost:8888/druid,可以看到如下图:

输入账号密码admin,admin,如下图

然后这时我们可以访问http://localhost:8888/saveCity?cityName=北京&cityIntroduce=中国首都

然后点击导航上面的SQL监控,如下图,

从上图可以看到启动项目创建表的sql已经刚刚执行的sql。到这里整合已经完成了。

原文发布于微信公众号 - 编程坑太多(idig88)

原文发表时间:2018-04-15

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏用户2442861的专栏

ubuntu16安装nginx

https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-...

1572
来自专栏乐沙弥的世界

Failed to create or upgrade OLR

    对于Oracle 11g RAC 的安装,与Oracle 10g(clusterware)类似,grid 安装完毕后需要执行orainstroot.sh...

914
来自专栏owent

GCC 7和LLVM+Clang+libc++abi 4.0的构建脚本

之前的版本发完,有空来更新一下之前的gcc和llvm+clang工具链的编译脚本了。其实GCC 7是才release没多久但是llvm 4.0发布其实有一段时间...

801
来自专栏搜云库

Spring Boot 中使用 MyBatis 整合 Druid 多数据源

本文将讲述 spring boot + mybatis + druid 多数据源配置方案。 环境 CentOs7.3 安装 MySQL 5.7.19 二进制版本...

3437
来自专栏dalaoyang

SpringBoot整合Jpa

上一篇介绍了springboot简单整合mybatis的教程。这一篇是介绍springboot简单整合jpa的教程。 由于jpa的功能强大,后续会继续写关于jp...

48711
来自专栏Urahara Blog

PHP Disabled_functions Bypass

5964
来自专栏cmazxiaoma的架构师之路

Servlet的那些事

1614
来自专栏IT进修之路

原 荐 SpringBoot整合mybati

1944
来自专栏乐沙弥的世界

ORA-27102: out of memory 故障

      最近的UAT数据库迁移,由于是多个DB需要迁移到同一台机器,一部分完成后,启动后续数据库碰到了ORA-27102错误,提示内存超出,查看系统可用内存...

842
来自专栏好好学java的技术栈

spring Aop实现身份验证和springboot异常统一处理

一般,如果用户没有登录的话,用户只可以查看商品,但是其他的,比如支付等是不能够进行操作的,这个时候,我们就需要用到用户拦截, 或者说身份验证了。

2291

扫码关注云+社区

领取腾讯云代金券