How does Spring Boot monitor SQL operation?

Today I want to talk to you about the monitoring function in Druid.

I believe that many small partners have used Druid database connection pool. Personally, Druid is a relatively successful open source project in Alibaba. Unlike Fastjson, Druid has always been excellent in all aspects, with complete functions, convenient use, and basic usage. Without further ado, let's take a look at the monitoring functions in Druid today.

1. Preparations

First, let's create a Spring Boot project, introduce MyBatis, etc., as follows:

Choose MyBatis and MySQL drivers and make a simple test case.

Let's connect to the database first:

spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql:///test05?serverTimezone=Asia/Shanghai

Create a User entity class and do a simple query case, as follows:

public class User {
    
    
    private Integer id;
    private String username;
    private String address;
    private String password;
    private String email;
    //省略 getter/setter
}
@Mapper
public interface UserMapper {
    
    
    List<User> getUserByUsername(String username);
}
@Service
public class UserService {
    
    
    @Autowired
    UserMapper userMapper;
    public List<User> getUserByUsername(String username){
    
    
        return userMapper.getUserByUsername(username);
    }
}
@RestController
public class UserController {
    
    
    @Autowired
    UserService userService;

    @GetMapping("/user")
    public List<User> getUser(String username) {
    
    
        return userService.getUserByUsername(username);
    }
}

UserMapper.xml is as follows:

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.javaboy.druid_monitor.mapper.UserMapper">
    <select id="getUserByUsername" resultType="org.javaboy.druid_monitor.model.User">
        select * from user where username=#{username}
    </select>
</mapper>

A very simple test, not much to say.

Everyone is free to build this environment. If you already have a persistent case, then go directly to the second section to introduce Druid.

Now the default database connection pool used in this project is HikariDataSource, which is the default database connection pool in Spring Boot. In fact, this is not bad.

2. Introducing Druid

Next we introduce Druid:

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

Note that the Druid introduced by Spring Boot is the above, which will be more convenient when configuring monitoring in the future.

Next, we configure WebStatFilter in application.properties. WebStatFilter is used to collect data related to web-jdbc monitoring:

# 启用 WebStatFilter
spring.datasource.druid.web-stat-filter.enabled=true
# 配置拦截规则
spring.datasource.druid.web-stat-filter.url-pattern=/*
# 排除一些不必要的 url,这些 URL 不会涉及到 SQL 查询
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
# 开启 session 统计功能
spring.datasource.druid.web-stat-filter.session-stat-enable=true
# 缺省 sessionStatMaxCount 是 1000 个,我们可以按需要进行配置
spring.datasource.druid.web-stat-filter.session-stat-max-count=1000
# 配置 principalSessionName,使得 druid 能够知道当前的 session 的用户是谁
# 根据需要,这个参数的值是 user 信息保存在 session 中的 sessionName
#spring.datasource.druid.web-stat-filter.principal-session-name=
# 下面这个配置的作用和上面配置的作用类似,这个是通过 Cookie 来识别用户
#spring.datasource.druid.web-stat-filter.principal-cookie-name=
# 开启 profile 后就能够监控单个 URL 地址调用列表
#spring.datasource.druid.web-stat-filter.profile-enable=

We can configure the first five, and the last three do not need to be configured. The meaning of each configuration has been listed in the code.

Next, open the configuration of StatViewServlet, as follows:

# 启用内置的监控页面
spring.datasource.druid.stat-view-servlet.enabled=true
# 内置监控页面的地址
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
# 开启 Reset All 功能
spring.datasource.druid.stat-view-servlet.reset-enable=true
# 设置登录用户名
spring.datasource.druid.stat-view-servlet.login-username=javaboy
# 设置登录密码
spring.datasource.druid.stat-view-servlet.login-password=123
# 白名单(如果allow没有配置或者为空,则允许所有访问)
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
# 黑名单(deny 优先于 allow,如果在 deny 列表中,就算在 allow 列表中,也会被拒绝)
spring.datasource.druid.stat-view-servlet.deny=

Configure the page address and configure the black and white list.

It should be noted that even if the reset-enable property is set to false, the reset button will be displayed, but clicking the button will not reset it.

OK, that's it.

3. Test

Ok, let's start the Spring Boot project for testing.

After the Spring Boot project is successfully started, first visit the following address:

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

At this point we will see the login authentication page, as follows:

Enter the username/password (javaboy/123) we configured earlier to log in. After logging in successfully, you can see the following page:

As you can see from the title bar, data source, SQL monitoring, SQL firewall and other functions are all available.

Next, we access the http://localhost:8080/user?username=aaaaddress and execute a SQL. After the execution is complete, let's view the SQL monitoring:

As you can see, there is a monitoring record of SQL execution at this point.

Other monitoring data can also be seen, I will not list them one by one. If you feel that the data displayed here is not intuitive, and you want to draw HTML pages yourself, that's okay. Click the JSON API at the end, you can see the JSON address of each monitoring item, and you can display it as you want with JSON. show.

4. Go Ads

If you want to use this monitoring page directly, this one has Ali's advertisement on it, as shown in the figure below, if the company uses it, it will be very awkward:

We might want to get rid of this ad, which is easy too.

First, after analysis, we found that the ad is built from a file called common.js, which is located druid-1.2.8.jar!/support/http/resources/js/common.jshere , and the common.js file has the following lines:

init : function() {
    
    
	this.buildFooter();
	druid.lang.init();
},
buildFooter : function() {
    
    
	var html ='';
	$(document.body).append(html);
},

The general logic is as above, the buildFooter method is responsible for building the advertisement at the end of the page, and the call to the buildFooter method is completed in the init method.

So if you want to remove ads, just don't call the buildFooter method.

So our idea of ​​advertising is also very simple, write a filter, intercept the request to common.js, and then make a little modification, as follows:

@WebFilter(urlPatterns = "/druid/js/common.js")
public class RemoveAdFilter implements Filter {
    
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        String text = Utils.readFromResource("support/http/resources/js/common.js");
        text = text.replace("this.buildFooter();", "");
        servletResponse.getWriter().write(text);
    }
}

It can be seen that this filter is to intercept the /druid/js/common.jsrequest . After intercepting, read the common.js file in the file by yourself, then manually replace this.buildFooter();this sentence, and finally write the file out.

Of course, remember to scan the Filter in the startup class, as follows:

@SpringBootApplication
@ServletComponentScan("org.javaboy.druid_monitor.filter")
public class DruidMonitorApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(DruidMonitorApplication.class, args);
    }

}

Okay, that's it, with this filter the ads are gone.

You can download this case by replying to druid_monitor in the background of the official account.

References:

  • https://github.com/alibaba/druid/wiki/

Guess you like

Origin blog.csdn.net/u012702547/article/details/122941479