SpringBoot之JDBC和Druid

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

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


<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.8version>
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> getDepartmentList(){

        List> mapList = jdbcTemplate.queryForList("select * from department");

        return mapList;
    }
}

访问结果:
SpringBoot之JDBC和Druid_第1张图片

使用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,但是有个问题:
SpringBoot之JDBC和Druid_第2张图片
原因:

@ConfigurationProperties(
    prefix = "spring.datasource"
)
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
    private ClassLoader classLoader;
    private String name;
    private boolean generateUniqueName;
    private Class type;
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    private String jndiName;
    private DataSourceInitializationMode initializationMode;
    private String platform;
    private List schema;
    private String schemaUsername;
    private String schemaPassword;
    private List 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();
    }
}

调试结果:
SpringBoot之JDBC和Druid_第3张图片

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 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 initParams = new HashMap<>();
        initParams.put("exclusions", "*.js, *.css, /druid/*");
        bean.setInitParameters(initParams);
        // 设置拦截路径
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

访问:

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

SpringBoot之JDBC和Druid_第4张图片
使用配置类里配置的账号密码登录即可。

你可能感兴趣的:(【框架】SpringBoot,【SpringBoot】)