springboot+mybatis+druid的配置(sql监控平台)

1.依赖

<!-- mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2.配置yml

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/newsell?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
     #把默认数据源切换成druid
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      db-type: mysql
      initial-size: 10 # 初始化连接数
      min-idle: 10
      max-active: 20 # 最大连接数
      max-wait: 60000 # 连接超时时间
      filter:
        stat:
          enabled: true
          log-slow-sql: true  # 开启mansql监控
          slow-sql-millis: 2000 # 超过2ms就是慢sql 
          merge-sql: false
      break-after-acquire-failure: true  # 开启重连机制
      connection-error-retry-attempts: 2 # 尝试重连两次

mybatis:
  mapper-locations: classpath:mapper/*.xml
  configuration:
    # 打印语句
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # 自动转换驼峰
    map-underscore-to-camel-case: true

3.druid配置类

package com.zykj.newsell.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * druid配置类
 *
 * @author lc
 * @version 1.0
 * @date 2022/4/20 10:20
 */
@Configuration
public class DruidConfig {
    private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);
    @Bean
    public DataSource createDruidDataSource(){
        DataSource dataSource= DruidDataSourceBuilder.create().build();
        return dataSource;
    }

    @Bean
    public ServletRegistrationBean druidServlet(){

        logger.info("init Druid Servlet Configuration ");
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();
        // 设置监控页面的登录名和密码以及连接ip
        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        //initParams.put("deny","黑名单的ip");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        initParams.put("resetEnable", "false");

        bean.setInitParameters(initParams);
        return bean;
    }

    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
        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;
    }

}

4.验证druid的监控网页

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

输入配置类中配置的密码
在这里插入图片描述

在这里插入图片描述

5. 配合springsecurity的情况

要关闭csrf或者开启csrf但是对druid忽略,而且/druid/**的路径忽略不验证-----修改security的配置类

 // 认证的处理
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
               // .csrf().ignoringAntMatchers("/druid/*").and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/user/register", "/user/login", "/user/logout", "/user/logout",
                        "/three/total/getQHLToken", "/user/set/pw",

                        "/druid/**",

                        "/doc.html/**", "/swagger-ui.html/**", "/webjars/**",
                        "/v2/api-docs",//swagger api json
                        "/swagger-resources/configuration/ui",//用来获取支持的动作
                        "/swagger-resources",//用来获取api-docs的URI
                        "/swagger-resources/configuration/security",//安全选项
                        "/swagger-ui.html").anonymous()    // 忽视的路径
                .anyRequest().authenticated();

        // 添加token过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //允许跨域
        http.cors();
    }

6.注意事项

进入druid的web监控页面

6.1 数据源报(*) property for user to setup

在这里插入图片描述

第一次你会发现报数据源那一栏报(*) property for user to setup,这是因为你的代码没有调用过sql,调用一下就好了

6.2 数据源的filter类名是空

这种情况就会导致SQL监控那一栏就不会有数据,修改一下配置文件

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/newsell?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    druid:
      db-type: mysql
      initial-size: 3 # 初始化连接数
      max-active: 8 # 最大连接数
      max-wait: 60000 # 连接超时时间
      filter:
        stat:
          enabled: true
          log-slow-sql: true
          slow-sql-millis: 1000
          merge-sql: false

正常的应该是这样的
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
### 博客管理系统 ### #Springboot ## 主要功能 * 系统用户,角色,权限增删改查,权限分配,权限配色 * 文件上传可自由选择本地存储,七牛云存储,阿里云存储 * 系统字典 * 配置网站基本信息,包括博客数据限制 * 查看系统关键操作的日志(可在系统后台自动定制需要监控的模板) * 在线新增数据库并直接生成 前,后台基本源码,放到源码相应目录中重启tomcat可直接使用,预览 * 系统定时任务的新增改查 立即启动 暂停 恢复 ## 技术框架 * 核心框架:`SpringBoot` * 安全框架:`Apache Shiro 1.3.2` * 缓存框架:`Redis 4.0` * 搜索框架:`Lucene 7.1` * 任务调度:`quartz 2.3` * 持久层框架:`MyBatis 3` mybatisplus 2.1.4 * 数据库连接池:`Alibaba Druid 1.0.2` * 日志管理:`SLF4J 1.7`、`Log4j` * 前端框架:`layui` * 后台模板:layuicms 2.0。 * 富文本:wangEditor ### 开发环境 建议开发者使用以下环境,这样避免版本带来的问题 * IDE:`eclipse`/`idea` * DB:`Mysql5.7` `Redis` * JDK:`JAVA 8` * WEB:Tomcat8 (采用springboot框架开发时,并没有用到额外的tomcat 用的框架自带的) # 运行环境 * WEB服务器:`Weblogic`、`Tomcat`、`WebSphere`、`JBoss`、`Jetty` 等 * 数据库服务器:`Mysql5.5+` * 操作系统:`Windows`、`Linux` (Linux 大小写特别敏感 特别要注意,还有Linux上没有微软雅黑字体,需要安装这个字体,用于生成验证码) #用户名:admin 密码:123456 #数据库文件:mysiteforme.sql #数据库配置文件:mysiteforme下的src/main/resources下的application.yml #启动文件:mysiteforme下的com.mysiteforme.admin下的MysiteformeApplication.java #注意:启动之前先启动redis # http://localhost:8080 管理员用户名:test 密码:1
在Java SpringBoot项目中,如果使用了Mybatis框架,默认情况下执行的所有SQL操作都不会打印日志。但是有时候我们需要对一些错误的语句进行排查,这时候就需要配置打印SQL日志。有两种常见的配置方法可以实现这个目的。 第一种方法是在application.properties文件中添加如下配置: ``` mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl ``` 但是有些情况下这种配置可能不起作用。 第二种方法是在application.yml文件中添加如下配置: ``` logging: level: com.xxx.webapp.dao: DEBUG ``` 其中`com.xxx.webapp.dao`是你的DAO接口包的层级目录,根据你的项目实际情况进行配置。这样配置后,Mybatis会打印SQL日志。 另外,你也可以通过编程方式配置打印SQL语句。例如,在Mybatis配置类中添加如下代码: ```java MybatisConfiguration configuration = new MybatisConfiguration(); configuration.setJdbcTypeForNull(JdbcType.NULL); configuration.setMapUnderscoreToCamelCase(true); configuration.setCacheEnabled(false); configuration.setLogImpl(StdOutImpl.class); bean.setConfiguration(configuration); ``` 这样配置后,Mybatis也会打印SQL日志。 #### 引用[.reference_title] - *1* [SpringBoot+Mybatis打印sql语句](https://blog.csdn.net/qq_46086108/article/details/121698059)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [springboot+mybatis项目sql日志打印配置](https://blog.csdn.net/egegerhn/article/details/124036337)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [springboot+mybatis-plus 两种方式打印sql语句](https://blog.csdn.net/snlx258/article/details/117225671)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LC超人在良家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值