How to count the active sessions in CF

After my success playing around with the underlying java that handles the application scope I was inspired to try the same on the session scope.

Get current sessions

One of the most commonly requested stats a site owner wishes to know is how many people are on their site at a moment in time. Coldfusion doesn't give an inbuilt way to get this information, but a bit of hacking in the cfusion jar file and introspection of the objects gives us what we need.

<cffunction name="getSessionCount" returntype="numeric" output="false">
   <cfset var oSession = createObject("java","coldfusion.runtime.SessionTracker")>
   <cfreturn oSession.getSessionCount()>
</cffunction>

Get current sessions per application

But then we may have a number of applications running on our site - and we want to see what the breakdown of activity is among each of our applications.

<cffunction name="getApplicationSessionCount" returntype="numeric" output="false">
   <cfargument name="appName" type="string" required="true">
   <cfscript>
   var oSession = createObject("java","coldfusion.runtime.SessionTracker");
   var mySessions= oSession.getSessionCollection(arguments.appName);
   return StructCount(mySessions);
   </cfscript>
</cffunction>

By passing in the application name this will return the number of sessions for a particular application. Neato.

If you link this code up with the the Application scope hackery you can create a nice table of session counts for all you applications.

Comments
Comments are not allowed for this entry.
BlogCFC was created by Raymond Camden. This blog is running version 5.1.004.