Springboot JdbcTemplate使用druid连接池

1、配置文件

  datasource:
    url: jdbc:mysql://localhost:3306/XXX?readOnlyPropagatesToServer=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&&useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

    druid:
      type: com.alibaba.druid.pool.DruidDataSource
      validation-query: SELECT 1
      pool-prepared-statements: true
      validation-query-timeout: 5000
      query-timeout: 3000
      initial-size: 5
      min-idle: 5
      max-active: 20
      max-wait: 10000
      test-while-idle: true
      test-on-return: true
      test-on-borrow: true
      # 空闲连接回收的时间间隔,与test-while-idle一起使用,设置5分钟
      time-between-eviction-runs-millis: 300000
      # 连接池空闲连接的有效时间 ,设置30分钟
      min-evictable-idle-time-millis: 1800000

2、自定义数据源

@Component
public class DruidProperties {
  @ConfigurationProperties(prefix = "spring.datasource")
  @Bean
  public DataSource druidDataSource() {
    return new DruidDataSource();
  }
}

3、创建JdbcTemplate连接

@Slf4j
public class MysqlService {

  /**
   * Spring Boot 默认已经配置好了数据源,可以直接 DI 注入然后使用即可
   */
  @Resource
  DataSource dataSource;

  public List> getSqlReturn(String sql){
    //获取jdbctemplate
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    List> query = jdbcTemplate.queryForList(sql);
    return query;
  }
}

 

你可能感兴趣的:(记录,spring,boot,JdbcTemplate,druid)