本文介绍了Spring Boot:计算页面浏览量 - 执行器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算每个端点上的观看次数.这个想法是为所有端点创建一个通用的请求计数映射,它应该基于动态输入的端点返回视图计数.

假设有人想检查 http://localhost:8080/user/101 上的观看次数.

  1. RequestMapping path =/admin/count &RequestParam = url (这里/user/101)
  2. 然后创建基于RequestParam的动态请求http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
  3. 获取并返回动态请求的响应 (JSON Object)并获取COUNT
  4. 的值

我坚持如何将动态请求发送到http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101并返回它的响应并获取计数值

@RequestMapping(path="/admin/count",method=RequestMethod.POST)public JSONObject count(@RequestParam(name="url") final String url)//@PathVariable(name="url") final String url{String finalURL = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + url + "";返回 sendRequestToURL(finalURL);}
@RequestMapping(path="/{finalURL}",method=RequestMethod.GET)public JSONObject sendRequestToURL(@PathVariable("finalURL") String url){//这里如何返回响应}

这是我直接触发 URL 时得到的

GET:http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101

 {"name": "http.server.requests",描述":空,"baseUnit": "秒",测量":[{统计":计数",价值":1},{"统计": "TOTAL_TIME",价值":0.3229436},{"统计": "MAX",价值":0.3229436}],可用标签":[{"标签": "例外",价值观":[无"]},{"标签": "方法",价值观":[获取"]},{"tag": "结果",价值观":[成功"]},{"标签": "状态",价值观":[200"]}]}

环境:

 `spring boot 2.1.2.RELEASE`<java.version>1.8</java.version><依赖><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></依赖>
解决方案

这个想法是你将从用户那里获得 endPoint 以显示将使用@RequestParam 完成的视图计数.根据请求端点创建 URLtoMap 根据您的要求

(即方法、状态、结果、异常等,例如 http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101&tag=method:GET).

@RequestMapping(path="/admin/count",method=RequestMethod.POST)public int count(@RequestParam(name="endPoint") final String endPoint) 抛出 IOException, JSONException{final String URLtoMap = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + endPoint + "";返回 sendRequestToURL(URLtoMap);}

现在基于 URLtoMap 使用 HttpURLConnection 发送请求并使用 BufferedReader 获取输出.当我使用 Spring Security 时,我被重定向到登录页面.为了解决这个问题,我在 SecurityConfig 文件中添加了 antMatchers,如下所示.如果您遇到 JSONException: Value of type java.lang.String cannot be convert to JSONObject 然后参考 this

public int sendRequestToURL(@PathVariable("URLtoMap") String URLtoMap) 抛出 IOException, JSONException{整数计数 = 0;StringBuilder 结果 = new StringBuilder();URL url = 新 URL(URLtoMap);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));字符串线;while ((line = rd.readLine()) != null) {结果.追加(行);}rd.close();试试{JSONObject jsonObject =new JSONObject(result.toString().replace("\"", ""));JSONObject jsonCountObject = new JSONObject(jsonObject.getJSONArray("measurements").get(0).toString());count =(int) jsonCountObject.get("value");}捕获(JSONException e){e.printStackTrace();}返回计数;}

安全配置

@Overrideprotected void configure(HttpSecurity http) 抛出异常{http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().antMatchers(HttpMethod.GET,"/actuator/**").permitAll().antMatchers(HttpMethod.POST,"/actuator/**").permitAll()}

pom.xml

<groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId></依赖><依赖><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></依赖><依赖><groupId>org.json</groupId><artifactId>json</artifactId><version>20090211</version></依赖>

导入正确的包

import org.json.JSONException;导入 org.json.JSONObject;导入 java.net.URL;导入 java.net.HttpURLConnection;导入 java.io.BufferedReader;导入 java.io.IOException;导入 java.io.InputStreamReader;

I have a requirement to count the views on each endpoint. The idea is to create one common Request Count Mapping for all endpoints which should return the view count based on a dynamically entred endpoint.

Let's say someone wants to check the view counts on http://localhost:8080/user/101.

  1. RequestMappping path = /admin/count & RequestParam = url (Here/user/101)
  2. Then create the dynamic Request based on RequestParamhttp://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
  3. Get and Return the Response of dynamic Request (JSON Object) and get the value of COUNT


@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public JSONObject count(@RequestParam(name="url") final String url)//@PathVariable(name="url") final String url
{
    String finalURL = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + url + "";
    return sendRequestToURL(finalURL);
}


@RequestMapping(path="/{finalURL}",method=RequestMethod.GET)
public JSONObject sendRequestToURL(@PathVariable("finalURL") String url)
{
    //How to return the response Here
}


This is what I get when Directly fire the URL

  {
    "name": "http.server.requests",
    "description": null,
    "baseUnit": "seconds",
    "measurements": [
        {
            "statistic": "COUNT",
            "value": 1
        },
        {
            "statistic": "TOTAL_TIME",
            "value": 0.3229436
        },
        {
            "statistic": "MAX",
            "value": 0.3229436
        }
    ],
    "availableTags": [
        {
            "tag": "exception",
            "values": [
                "None"
            ]
        },
        {
            "tag": "method",
            "values": [
                "GET"
            ]
        },
        {
            "tag": "outcome",
            "values": [
                "SUCCESS"
            ]
        },
        {
            "tag": "status",
            "values": [
                "200"
            ]
        }
    ]
}


Environment:

    `spring boot 2.1.2.RELEASE`
    <java.version>1.8</java.version>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
解决方案

The idea is you will get the endPoint from user to display to show the view counts which will be done using @RequestParam. Based on the request endPoint create the URLtoMap according to your requirements

(i.e methods, status, outcome, exception etc, e.g. http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101&tag=method:GET).


@RequestMapping(path="/admin/count",method=RequestMethod.POST)
    public int count(@RequestParam(name="endPoint") final String endPoint) throws IOException, JSONException
    {
        final String URLtoMap = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + endPoint + "";
        return sendRequestToURL(URLtoMap);
    }


Now Based on the URLtoMap send Request using HttpURLConnection and get the output using BufferedReader. As I am using Spring Security I was redirected to Login Page. To solve the problem I have added antMatchers in SecurityConfig file as below. If you facing JSONException: Value of type java.lang.String cannot be converted to JSONObject then refer this

public int sendRequestToURL(@PathVariable("URLtoMap") String URLtoMap) throws IOException, JSONException
{
      int count = 0;
      StringBuilder result = new StringBuilder();
      URL url = new URL(URLtoMap);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
         result.append(line);
      }
      rd.close();

      try {
            JSONObject jsonObject =new JSONObject(result.toString().replace("\"", ""));
            JSONObject jsonCountObject = new JSONObject(jsonObject.getJSONArray("measurements").get(0).toString());
            count =(int) jsonCountObject.get("value");
        }
        catch (JSONException e) {
            e.printStackTrace();
        }

      return count;
}


@Override
        protected void configure(HttpSecurity http) throws Exception{

             http
             .csrf().disable()
             .authorizeRequests().antMatchers("/login").permitAll()
             .antMatchers(HttpMethod.GET,"/actuator/**").permitAll()
             .antMatchers(HttpMethod.POST,"/actuator/**").permitAll()
}
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20090211</version>
</dependency>
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

这篇关于Spring Boot:计算页面浏览量 - 执行器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 09:41
查看更多