Spring Boot:计算页面视图 - 执行器

问题描述 投票:1回答:2

我需要计算每个端点上的视图。我们的想法是为所有端点创建一个公共请求计数映射,该映射应根据动态获取的端点返回视图计数。

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

  1. RequestMapping qazxsw poi
  2. 然后创建path = /admin/count & RequestParam = url (Here /user/101) dynamic Request based on RequestParam
  3. 动态请求http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101Get and Return the Response并获得(JSON Object)的值

我坚持如何将COUNT发送到dynamic request并返回它的响应并获得计数值


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 + "";
    return sendRequestToURL(finalURL);  
}

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

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

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

环境:

  {
    "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"
            ]
        }
    ]
}
java spring spring-boot spring-boot-actuator
2个回答
1
投票

所以你想用 `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> 封装actuator/metrics

在Java中调用Rest API有很多种方法和库

我将添加最简单的一个

像这样的东西

/admin/count

编辑1:

你快到了。只需要将String解析为JSONObject。试试吧

public JSONObject sendRequestToURL(@PathVariable("finalURL") String urlToRead)
{
      StringBuilder result = new StringBuilder();
      URL url = new URL(urlToRead);
      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();
      return new JSONObject(result.toString());  // org.json
}

编辑2:

我猜你有Spring Security。

当你在内部调用API时,Spring将其视为需要身份验证的外部调用。

作为解决方法,您可以从安全上下文中排除String strJson = result.toString().replace("\\\"","'"); JSONObject jo = new JSONObject(strJson.substring(1,json.length()-1)); return jo; API。

/actuator

或者用XML

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
     .antMatchers("/actuator*").permitAll()

     ...
}

希望Spring安全性会忽略此URL,您将无法获得登录表单。


1
投票

我们的想法是,您将从用户获取endPoint以显示将使用@RequestParam完成的视图计数。 <security:http auto-config="true" use-expressions="true" > <security:intercept-url pattern="/actuator*" access="permitAll"/> ... </security:http> 根据您的要求

Based on the request endPoint create the URLtoMap


(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); } 使用URLtoMap发送请求并使用HttpURLConnection获取输出。当我使用Spring Security时,我被重定向到Login Page。为了解决这个问题,我在SecurityConfig文件中添加了antMatchers,如下所示。如果你面对BufferedReader,那么请参考JSONException: Value of type java.lang.String cannot be converted to JSONObject

this

SecurityConfig

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;
}

pom.hml

@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>
© www.soinside.com 2019 - 2024. All rights reserved.