案例: 模拟登陆,获取Druid SQL监控数据

Posted 袁义锐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了案例: 模拟登陆,获取Druid SQL监控数据相关的知识,希望对你有一定的参考价值。

本文重在编写模拟登陆的代码;Druid SQL监控 admin 平台,重在辅助验证;

本案例采用springboot框架;

1.jar包版本信息:

<!-- alibaba的druid数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.20</version>
		</dependency>

2. 数据库连接池配置信息:

spring:
    datasource:
        name: monitor
        type: com.alibaba.druid.pool.DruidDataSource
        druid:
          filters: stat
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://IP:PORT/DATABASE?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
          username: root
          password: root
          initial-size: 1
          min-idle: 1
          max-active: 20
          max-wait: 60000
          time-between-eviction-runs-millis: 60000
          min-evictable-idle-time-millis: 300000
          validation-query: SELECT 'x'
          test-while-idle: true
          test-on-borrow: false
          test-on-return: false
          pool-prepared-statements: false
          max-pool-prepared-statement-per-connection-size: 20

3.DruidConfiguration配置代码:

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 com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * <p>类描述</p>
 *
 * @author yuanyirui
 * @Date 2020年1月3日 上午10:21:22
 */
@Configuration
public class DruidConfiguration 

    @Bean
    public ServletRegistrationBean statViewServle() 
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //IP白名单
        //servletRegistrationBean.addInitParameter("allow","192.168.1.12,127.0.0.1");
        //IP黑名单
        //servletRegistrationBean.addInitParameter("deny","192.168.4.23");
        //控制台用户
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        //是否能够重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    

    @Bean
    public FilterRegistrationBean statFilter() 
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //添加过滤规则
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
//        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico");
        return filterRegistrationBean;
    

4.启动项目,登陆地址:

http://localhost:9008/monitor/druid/login.html

如上配置:

用户名和密码同为:admin

 

druid sql API地址:http://localhost:9008/monitor/druid/sql.json

 

5.模拟登陆,后去sql数据

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;


public class MockDruidLogin 
    static String druidCookie = "JSESSIONID=3DB050C51ECF84554EE37245DE0CD00A";
    // 登陆 Url
    static String loginUrl = "http://localhost:9008/monitor/druid/submitLogin?loginUsername=admin&loginPassword=admin";
    // 需登陆后访问的 Url
    static String dataUrl = "http://localhost:9008/monitor/druid/sql.json?orderBy=SQL&orderType=desc&page=1&perPageCount=1000000&";

    static String headerUrl = "http://localhost:9008/monitor/druid/header.html";

    public static void main(String[] args) 
        while (true) 
            try 
                login();
                Thread.sleep(800);
             catch (Exception e) 
                e.printStackTrace();
            
        
//
    

    private static void login() 
        try 

            HttpClient httpClient = new HttpClient();
            // 模拟登陆,按实际服务器端要求选用 Post 或 Get 请求方式
            PostMethod postMethod = new PostMethod(loginUrl);
            // 设置登陆时要求的信息,用户名和密码
            NameValuePair[] data = new NameValuePair("loginUsername", "admin"),
                    new NameValuePair("loginPassword", "admin");
            postMethod.setParameter("Cookie", druidCookie);
            postMethod.setRequestBody(data);
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            httpClient.getParams().setParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
           httpClient.executeMethod(postMethod);


          //  postMethod.getResponseBody();
            // 获得登陆后的 Cookie
            Cookie[] cookies = httpClient.getState().getCookies();

            StringBuffer tmpcookies = new StringBuffer();
            for (Cookie c : cookies) 
                tmpcookies.append(c.toString() + ";");
                System.out.println("cookies = " + c.toString());
            
            System.out.println("模拟登录成功");


            GetMethod getMethod = new GetMethod(dataUrl);
            getMethod.setRequestHeader("cookie", druidCookie);
            //核心点是在这里重新设置了cookie
            postMethod.setRequestHeader("Referer", headerUrl);
            postMethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
            httpClient.executeMethod(getMethod);

            String text = getMethod.getResponseBodyAsString();
//            System.out.println("获取到SQL返回值: " + text);

            JSONObject jsonObject = JSONObject.parseObject(text);


            JSONArray content = jsonObject.getJSONArray("Content");
            if (content != null&&!content.isEmpty()  ) 
                for (Object o : content) 
                    JSONObject cont = (JSONObject) o;
                    String sql = cont.getString("SQL");
//                    System.out.println("获取到SQL: " + sql);
                    String pureSql = sql.replaceAll("\\\\n\\\\t\\\\t\\\\t", " ").replaceAll("\\\\t", " ").replaceAll("\\\\n", " ");
                    System.out.println("获取到SQL: " + pureSql.replaceAll("\\\\?", "1"));
                
            
            System.out.println("---------------------------------执行下一个循环---------------------------------");
         catch (Exception e) 
            e.printStackTrace();
        
    

 

 

以上是关于案例: 模拟登陆,获取Druid SQL监控数据的主要内容,如果未能解决你的问题,请参考以下文章

Druid连接池&Template组件&三级分层开发,模拟账号登陆

SpringBoot2.0 基础案例(07):集成Druid连接池,配置监控界面

springBoot小案例(登陆,增删改查)

springBoot小案例(登陆,增删改查)

为啥修改阿里druid连接池监控登录密码后登陆不成功

如何使用Druid监控sql