Fork me on GitHub

SpringBoot 之数据访问

1. Spring Boot 与 JDBC

  • 默认使用 org.apache.tomcat.jdbc.pool.DataSource 数据源;
// application.yml
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql:///jpa
    driver-class-name: com.mysql.jdbc.Driver
    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, 'wall' 用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500


// 配置Druid的属性,DruidConfig.java
@Configuration
public class DruidConfig{

    @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", "root");
        initParams.put("allow", "");        // 默认就是允许所有访问
        return bean;
    }

    // 2. 配置一个Web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*");    // 不拦截哪些请求

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));  // 拦截所有请求

        return bean;
    }
}

参考资料:

posted @ 2018-06-10 22:45  小a的软件思考  阅读(219)  评论(0编辑  收藏  举报