Получение точного количества запросов - PullRequest
0 голосов
/ 04 июня 2018

У меня есть этот код для подсчета запросов:

<cfobject type="JAVA" action="Create" name="thread" class="java.lang.Thread">

<!--- Get all stack traces from the thread object --->
<cfset stackTrace = thread.getAllStackTraces()>

<!--- Convert the entrySet into an array --->
<cfset stackArray = stackTrace.entrySet().toArray()>

<cfset requestCount = 0 />

<!--- Loop over the entrySet array --->
<cfloop from="1" to="#ArrayLen(stackArray)#" index="sIndex">
    <!--- Get the current thread values --->
    <cfset thisThread = stackArray[sIndex].getValue()>
    <!--- Loop over current thread values --->
    <cfloop from="1" to="#ArrayLen(thisThread)#" index="tIndex">
        <!--- Get the filename for this thread --->
        <cfset thisThreadFile = thisThread[tIndex].getFileName()>
        <!--- If the file name contains .cfm output it --->
        <cfif isDefined("thisThreadFile") AND thisThreadFile CONTAINS ".cfm">
            <cfset requestCount += 1 />
        </cfif>
    </cfloop>
</cfloop>

<cfset json_object = structNew()>
<cfset json_object["active_requests"] = JavaCast("int", requestCount)>

<cfoutput>#serializeJSON(json_object)#</cfoutput>

Мне нужно, чтобы я не мог считать кратные значения в трассировке стека.Каков наилучший способ сделать это?

1 Ответ

0 голосов
/ 04 июня 2018

Если вы имеете в виду только количество уникальных имен файлов, а не счетчик, используйте структуру.Структуры хранят только уникальные ключи.

Создать пустую структуру перед внешним циклом.Затем добавьте соответствующие имена файлов во внутренний цикл.(Я бы рекомендовал использовать isNull вместо isDefined и список функций для получения расширения файла)

<cfset uniqueFileNames = {}>
<cfloop from="1" to="#ArrayLen(stackArray)#" index="sIndex">
    ...
   <cfloop ....>
       <!--- If the file name ENDS with .cfm include it --->
       <cfif !isNull(thisThreadFile) && listLast(thisThreadFile, ".") eq "cfm">
           <cfset uniqueFileNames[thisThreadFile] = true>
       </cfif>
    </cfloop>
</cfloop>

Наконец, получите количество уникальных файлов с помощью structCount () :

<cfset json_object["active_requests"] =  structCount(uniqueFileNames)>

Предлагаемые улучшения

Поскольку вы используете 2016, переключение на циклы «массив» и сокращение структуры сделают код еще проще.Полный пример:

<cfset thread = createObject("java", "java.lang.Thread")>
<cfset allTraces = thread.getAllStackTraces()>
<cfset traceArray = allTraces.entrySet().toArray()>

<cfset uniqueFileNames = {}>
<cfloop array="#traceArray#" index="currThread">
    <cfloop array="#currThread.getValue()#" index="thisThread">
        <cfset thisThreadFile = thisThread.getFileName()>
        <cfif !isNull(thisThreadFile) AND lcase (thisThreadFile).endsWith(".cfm")>
            <cfset uniqueFileNames[thisThreadFile] = true>
        </cfif>
    </cfloop>
</cfloop>

<cfset json_object = {"active_requests" =  structCount(uniqueFileNames)}>
<cfoutput>#serializeJSON(json_object)#</cfoutput>
...