SpringBoot之JDBC和Druid

首先使用IDEA的Spring Initializr创建工程,添加Web、MySQL、JDBC模块

另外在pom.xml文件中导入Druid依赖:

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.8</version>
</dependency>

配置application.yml配置文件:

spring:
  datasource:
    username: root
    password: Root!!2018
    url: jdbc:mysql://192.168.3.18/jdbc?autoReconnect=true&useSSL=false
    driver-class-name: com.mysql.jdbc.Driver

在测试类中进行测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootWebJdbcDruidApplicationTests {

    @Autowired
    private DataSource dataSource;

    @Test
    public void contextLoads() throws SQLException {

        System.out.println(dataSource.getClass());

        Connection connection = dataSource.getConnection();

        System.out.println(connection);

        connection.close();
    }
}

控制台输出结果:

class com.zaxxer.hikari.HikariDataSource
HikariProxyConnection@1183572822 wrapping com.mysql.jdbc.JDBC4Connection@5c9ac4cc

结论:连接成功,默认使用的数据源是HikariDataSource

使用SpringBoot自动配置好的JdbcTemplate:

@Controller
public class DepartmentController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/departmentList")
    @ResponseBody
    public List<Map<String, Object>> getDepartmentList(){

        List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from department");

        return mapList;
    }
}

访问结果:
这里写图片描述

使用Druid数据源

application.yml

spring:
  datasource:
    username: root
    password: Root!!2018
    url: jdbc:mysql://192.168.3.18/jdbc?autoReconnect=true&useSSL=false
    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

在测试类中启动调试,查看DataSource
可以看到DataSource已经替换成Druid,但是有个问题:
这里写图片描述
原因:

@ConfigurationProperties(
    prefix = "spring.datasource"
)
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
    private ClassLoader classLoader;
    private String name;
    private boolean generateUniqueName;
    private Class<? extends DataSource> type;
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    private String jndiName;
    private DataSourceInitializationMode initializationMode;
    private String platform;
    private List<String> schema;
    private String schemaUsername;
    private String schemaPassword;
    private List<String> data;
    private String dataUsername;
    private String dataPassword;
    private boolean continueOnError;
    private String separator;
    private Charset sqlScriptEncoding;
    private EmbeddedDatabaseConnection embeddedDatabaseConnection;
    private DataSourceProperties.Xa xa;
    private String uniqueName;

配置文件的属性是与配置类绑定的,虽然配置文件有DruidDataSource的属性,但是SpringBoot自带的DataSource配置类没有相应的属性和方法,导致部分属性无法绑定,所以我们需要自定义Druid的数据源属性类

解决:往容器里加入自己的配置类,记得与相应属性(spring.datasource)绑定

@Configuration
public class DruidConfig {

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

调试结果:
这里写图片描述

Druid监控

修改application.yml

spring:
  datasource:
    username: root
    password: Root!!2018
    url: jdbc:mysql://192.168.3.18/jdbc?autoReconnect=true&useSSL=false
    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,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,logback
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

修改DruidConfig

@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/*");

        // 设置初始化参数,参数详情查看StatViewServlet
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "123456");
        initParams.put("allow", "");  // 默认允许所有访问
        //initParams.put("deny", "192.168.3.9");  // 拒绝访问

        bean.setInitParameters(initParams);

        return bean;
    }

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

        // 设置初始化参数,参数详情查看WebStatFilter
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js, *.css, /druid/*");
        bean.setInitParameters(initParams);
        // 设置拦截路径
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

访问:

http://localhost:8080/druid/login.html

这里写图片描述
使用配置类里配置的账号密码登录即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值