SpringBoot-整合JDBC-Druid

2023-12-27 06:16:16

依赖

<!--jdbc-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--druid连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>
<!--druid连接池需要配置log4j-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<!--数据库驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    <scope>runtime</scope>
</dependency>
<!--测试-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: root
    # 使用druid连接池
    type: com.alibaba.druid.pool.DruidDataSource
    # 配置初始化大小、最小、最大线程数
    initialSize: 5
    minIdle: 5
    # CPU核数+1,也可以大些但不要超过20,数据库加锁时连接过多性能下降
    maxActive: 20
    # 最大等待时间,内网:800,外网:1200(三次握手1s)
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最大空闲时间,毫秒
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1
    testWhileIdle: true
    # 设置从连接池获取连接时是否检查连接有效性,true检查
    testOnBorrow: true
    # 设置从连接池归还连接时是否检查连接有效性,true检查
    testOnReturn: true
    # 可以支持PSCache(提升写入、查询效率)
    poolPreparedStatements: true
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计
    filters: stat,wall,log4j
    # 保持长连接
    keepAlive: true
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Druid 配置类

  • http://localhost:8080/druid/sql.html 访问 druid 监控台
@Configuration
public class DruidConfig {
    // 绑定配置文件
    @ConfigurationProperties(prefix = "spring.datasource")
    // 注入数据源
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }
    // 后台监控
    // 注册到springboot内置的servlet容器
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        // 后台需要有人登录
        Map<String,String> initParameters = new HashMap<>();
        // 登录用户的key是固定的
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123456");
        // 允许谁可以访问:value为空则允许所有人
        initParameters.put("allow","");
        // 禁止谁访问
        initParameters.put("abcd","192.168.0.0");
        // 设置初始化参数
        bean.setInitParameters(initParameters);
        return bean;
    }
    // 注册过滤器
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        Map<String,String> initParameters = new HashMap<>();
        // 不统计这部分
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        // 设置初始化参数
        bean.setInitParameters(initParameters);
        return bean;
    }
}

controller

@RestController
public class jdbccontroller {
    // 事务是自动提交的
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @GetMapping("/userList")
    public List<Map<String, Object>> getUserList(){
        return jdbcTemplate.queryForList("select * from user");
    }
    @GetMapping("/addUser")
    public String addUser(){
        jdbcTemplate.update("insert into user values()");
        return "add-ok";
    }
    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id")int id){
        jdbcTemplate.update("update user set username = ? where id = " + id,"变长参数占位");
        return "update-ok";
    }
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        jdbcTemplate.update("delete from user where id = ?",id);
        return "delete-ok";
    }
}

文章来源:https://blog.csdn.net/h_e_l_l_o_______/article/details/135233885
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。