侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

SpringBoot(23)之切换数据源为Druid及配置监控

zze
zze
2018-04-14 / 0 评论 / 0 点赞 / 610 阅读 / 5711 字

当然,首先要引入依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.15</version>
</dependency>

方式一:配置数据源类型

通过上面的源码分析我们已经知道,如果我们要切换数据源,只需要配置 spring.datasource.type 为指定的数据源类型即可,如下:

# application.yml
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.202.135:3306/springboot_jdbc
    driver-class-name: com.mysql.jdbc.Driver
    schema:
      - classpath:myschema.sql
    data:
      - classpath:mydata.sql
    type: com.alibaba.druid.pool.DruidDataSource

测试:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DataJdbcApplicationTests {
    @Autowired
    public DataSource dataSource;

    @Test
    public void testDataSource() throws SQLException {
        System.out.println(dataSource.getClass());
        /*
        class com.alibaba.druid.pool.DruidDataSource
         */
    }
}

方式二:手动注册数据源

方式一其实有一个弊端,如果我们要使用 Druid 独有的配置,例如要配置 Druid 监控,仅仅在配置文件中是完成不了这个需求的,此时我们就需要手动注册数据源,并且手动将配置的属性的绑定到数据源实例。

配置:

# application.yml
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.202.135:3306/springboot_jdbc
    driver-class-name: com.mysql.jdbc.Driver
    # Durid 独有的属性
    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
    # 配置监控统计拦截的 filter ,去掉后监控界面无法统计,wall 用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

手动注册数据源 bean 并配置监控:

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;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DuridConfig {

    @ConfigurationProperties("spring.datasource") // 手动绑定配置属性
    @Bean
    public DataSource duridDataSource(){
        return new DruidDataSource();
    }

    // 配置 Druid 监控
    // 1、配置一个管理后台的 Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin"); // 登录后台的用户名
        initParams.put("loginPassword", "123456");
        initParams.put("allow",""); // 默认允许所有域名及 IP 访问
        initParams.put("deny","127.0.0.1"); // 拒绝 127.0.0.1 访问

        servletRegistrationBean.setInitParameters(initParams);

        return servletRegistrationBean;
    }
    // 2、配置一个监控的 filter
    @Bean
    public FilterRegistrationBean webStatFilter(){

        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        WebStatFilter webStatFilter = new WebStatFilter();
        filterRegistrationBean.setFilter(webStatFilter);
        Map<String, String> initParams = new HashMap<>();

        initParams.put("exclusions", "*.js,*.css,/druid/*");

        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        return filterRegistrationBean;
    }
}

测试:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DataJdbcApplicationTests {
    @Autowired
    public DataSource dataSource;

    @Test
    public void testDataSource() throws SQLException {
        System.out.println(dataSource.getClass());
        /*
        class com.alibaba.druid.pool.DruidDataSource
         */
    }
}

启动项目,可通过 localhost:8080/druid 访问到监控平台:
image.png

0

评论区