Improve scalability with the SessionCache service

30 June 2014
PDF (361 KB)
 
Photo of Paul Chen

Paul Chen

Senior Software Developer

Follow me on Google+

Photo of Brian Martin

Brian Martin

Distinguished Engineer, Websphere XS/DataPower XC10 Chief Architect

 

Photo of Abelard Chow

Abelard Chow

Advisory Software Developer

Follow me on Google+

Sign up for IBM Bluemix
This cloud platform is stocked with free services, runtimes, and infrastructure to help you quickly build and deploy your next mobile or web application.

As software architects, we know that clustering and load balancing are important topics in enterprise applications. However, we often don't have the resources to design and implement them. Well-designed session persistence framework is required for performance and scalability.

Fortunately, you can use the SessionCache service available through IBM Bluemix™ to help with scalability and performance management. This article shows you how to develop and deploy an application that takes advantage of the SessionCache service.

Using Bluemix and SessionCache service allows my enterprise application to scale easily.

Preface: HTTP session and session persistence

 

HTTP is one of the oldest internet technologies. HTTP sessions allow information to persist among multiple HTTP requests. The information, also known as session data, is stored in a machine's physical memory, which is fine when an application is small and only serves a few users. However, for enterprise applications that involve multiple servers and computer systems, session data may be shared across multiple machines for load balancing, clustering, fail-over, and other scalability usage scenarios. In this case, keeping session data in a single machine's memory is not good enough.

Session persistence means storing session data on a file system for sharing across multiple machines. Generally, a database is used to store session data for access from multiple servers, but a single database server that serves multiple web servers causes a bottleneck in the system. For better results, you can use multiple database servers, but data replication frequency between database servers then becomes a challenge. Replicating too often takes up system resources, while less frequent replication may cause data integration issues. Thankfully, IBM SessionCache Service can help.

SessionCache Service allows session data to be stored in an object grid, so enterprise applications scale easily with better performance and without any of the previously mentioned multiple database server issues.

In the Stone Age, application developers implemented session persistence. Today, since session persistence is so common, most application servers allow selection of a persistence target using server configurations. Application developers only interact with HTTP session APIs; the server configurations determine whether to persist and which technology to use for persistence.

Part 1: Deploy and run the sample application

 

Before you deploy the application in Bluemix, you must register. Go to Bluemix and click LOGIN. Follow the instructions to register or manage your account, then:

  1. Install Cloud Foundry client. Create a folder in your environment — for example, myWS. Download the cf command v6 into the folder you created. Run the downloaded file and follow the instruction to install Cloud Foundry client into the same folder.
  2. Create a folder in the Cloud Foundry folder — for example, "samples."
  3. Download sessionCacheSample.war file from IBM DevOps Services and save it in the folder you just created. Note: This sample application requires a SessionCache service named scsSampleSessionServiceDWDemo001. If you think that this name might result in a conflict, see "Add the server configuration" under Build a sample app in Part 2 to bind the application to a service with a different name.
  4. Deploy the WAR file to Bluemix.
    1. In the command prompt, change directories to your newly created samples folder. Use the command cf api https://api.ng.bluemix.net to connect to Bluemix.
    2. Log in to Bluemix using cf login and follow the prompts.
    3. Now, use cf push <app name> -p sessionCacheSample.war to deploy the WAR file, where <app name> is a unique application name. You will see similar messages when the push command is executed successfully and the application is running. Push successfully
    4. Create a SessionCache service instance for the application. Use cf create-service SessionCache free <service instance name> to create the service instance, where free is the service plan name, and <service instance name> is a unique name for the service instance. We used scsSampleSessionServiceDWDemo001 as the service instance name to match the configuration in the server xml.
    5. With the application deployed and service instance available, bind them together using cf bind-service <app name in Step c> <service instance name in Step d>.
    6. After the binding is done, it asks you to push the application again. Execute the command in Step C again. For more information, see Installing the cf tool.
  5. Test the sample application. Log in to Bluemix. You should see your sample application deployed from the dashboard. Click the link in the middle of the application icon to access the application and check the logs for errors. Try retrieving session data using the Retrieve Session Data button.
  6. Check the service status and space usage. After retrieving session data, go back to the Bluemix dashboard. In the navigation panel, click Apps and select the sample application deployed. In the Services section, click the link in the middle of the service to bring up the Service Status page. Review the Space Used, Throughput, and more.
  7. Optionally: Remove the sample application and service. In Bluemix, click Dashboard at the top of the screen. Click the setting icon at the upper-right corner of your application box and select Stop App. Click the setting icon at the upper right corner of your application box and select Delete App. In the window, check the boxes for your application and service in the SERVICES tab and ROUTES tab. Click OK to delete the sample application and service.

Part 2: Set up the environment and build your own sample app

 

Before you start

 

To build the application in this article:

The source code of the sample application is available through IBM DevOps Services. To load the sample code and understand what it does, follow the following steps.

Step 1. Set up the environment

 

To build an application that uses the SessionCache service, you must set up the proper environment. You must install the Cloud Foundry client to deploy the SessionCache application in the IBM cloud environment. For development, you will need to install WebSphere® Application Server Liberty Profile and WebSphere eXtreme Scale. You must also have the Eclipse IDE already installed.

  1. Install Cloud Foundry client. Create a folder in your environment — for example, myWS. Download the cf command v6 into the folder you created. Run the downloaded file and follow the instruction to install Cloud Foundry client into the same folder.
  2. Install Liberty Profile. Download WebSphere Application Server Liberty Profile into the folder you created (for example, myWS). Follow the instructions to install Liberty Profile in the same folder. If asked for an installation location, press Enter to accept the default.
  3. Install WebSphere Extreme Scale. Download WebSphere eXtreme Scale for Developers Liberty Profile into the folder you created. Follow the instructions to install WebSphere eXtreme Scale in the same folder. If asked for the installation location, press Enter to accept default. After installation, the folder structure looks like this: Screen capture shows the folder structure after installationNote: The wxs is under the wlp folder.

Step 2. Build a sample app

 

After you complete your environment setup, you can start building a SessionCache application. There are two methods to build apps that run in Bluemix:

  • An app that deploys as a stand-alone WAR file
  • An app that deploys through a Liberty buildpack

In this article, we describe building a SessionCache app that deploys as a stand-alone WAR file. For more information about building an application that deploy through Liberty buildpack, see "Binding a DataCache service instance to Liberty Applications."

The source code of the sample application is available through IBM DevOps Services.

To build an app that deploys as a stand-alone WAR file:

  1. Add libraries. You must add a class of libraries to the project: Servlet 3.0 library. To add the Servlet 3.0 library, right-click on the project and select Properties to open the properties window. Select Java Build Path and switch to the Libraries tab. Click Add External JARs, navigate to the myWS/wlp/dev/api/ spec directory and select the com.ibm.ws.javaee.servlet.3.0_1.0.1.jar file. Adding Servlet 3.0 library
  2. The following code provides the option to request session data:
    private String getSessionData(HttpSession session) {    	
        	
           String response = "<H2>Information on your session:</H2>\n" +
            		"<TABLE BORDER=1>\n" +
            		"<TR> <TH>Info Type</TH> <TH>Value</TH> </TR>\n" +
         			"<TR> <TD>ID</TD> <TD>" + session.getId() + "</TD> </TR>\n" +
            		"<TR> <TD>isNew</TD> <TD>" + session.isNew() +  "</TD> </TR>\n" +
         			"<TR> <TD>Creation time</TD> <TD>" + new
    Date(session.getCreationTime()) + "</TD> </TR>\n" +
            		"<TR>	<TD>Time of Last Access</TD> <TD>" + new 
    Date(session.getLastAccessedTime()) + "</TD> </TR>\n" +
            		"<TR>	<TD>Max Inactive Interval</TD> <TD>" + 
    session.getMaxInactiveInterval() + "</TD> </TR>\n" +
            		"<TR>	<TD>Number of Previous Accesses</TD><TD><B>" + 
    session.getAttribute(attr_accessCount) + "</B></TD> </TR>\n" +
            		"</TABLE>\n";
            
         return response;
           }

    When the HTTP session API's getId() and isNew() is called, the application server will retrieve persisted session data using specified technology — in this case, the SessionCache service, based on the configurations in the server xml.
  3. The following code provides the option to invalidate session:
    	private String invalidateSession(HttpSession session) {
        	
        	  session.invalidate();
        	
            String response = "<h2>" + "Session invalidated. Please visit again!" + "</h2>\n";
            return response;
        	}

    When the HTTP session API's invalidate() is called, the application server will remove persisted session data using specified technology — in this case, the SessionCache service, based on configurations in the server xml.
  4. The following line in the doGet() method allows you to create or retrieve the session:
            HttpSession session = request.getSession(true);

    In the background, the application server will perform session persistence to create or to retrieve session data using the IBM SessionCache service. For more information about configuring an application server to use SessionCache service, please see the instructions related to server xml later in this article.
  5. The following code determines if it is the first time the session is being accessed:
            String heading = ""; 
       IntWrapper accessCount = (IntWrapper) session.getAttribute(attr_accessCount);        
       if (accessCount == null) { 
                accessCount = new IntWrapper(0); 
                heading = "Welcome, Newcomer."; 
          } else { 
                heading = "Welcome back."; 
                accessCount.incrementValue(); 
          } 
          session.setAttribute(attr_accessCount, accessCount);

    When the HTTP session API's getAttribute() and setAttribute() is called, the application server will perform session persistence using specified technology — in this case, SessionCache service, based on configurations in the server xml.
  6. Add the server configuration. After completing implementation of the SessionCache application, you must configure the application to use the SessionCache service in Bluemix. The configuration is in a file named server.xml, under the WebContent folder (.../ SessionCacheServiceSample / WebContent).

    Note: It uses a SessionCache service named scsSampleSessionServiceDWDemo001, which is created at deployment time. Use a unique service name for your application. Also, we recommend you set the idReuse attribute to true in the httpSession tag.

    <server description="Session Cache Service Sample">
    
        <featureManager>
            <feature>webProfile-6.0</feature>       
            <feature>eXtremeScale.webapp-1.1</feature>
            <feature>icap:appstate-1.0</feature>
        </featureManager>
    
        <xsWebApp id="mysession" 
            objectGridName="${cloud.services.scsSampleSessionServiceDWDemo001.
    connection.gridName}" 
            objectGridType="REMOTE" 
            catalogHostPort="${cloud.services.scsSampleSessionServiceDWDemo001.
    connection.catalogEndPoint}"
            securityEnabled="true"
    
    credentialGeneratorClass="com.ibm.websphere.objectgrid.security.plugins.builtins
    .UserPasswordCredentialGenerator" 
            credentialGeneratorProps="${cloud.services.scsSampleSessionServiceDWDemo001.
    connection.username}${cloud.services.scsSampleSessionServiceDWDemo001.connection.
    password}" />
    
        <httpSession idReuse="true" />
    				
        <application name="sessionCacheSample" context-root="/" location=
    "../../../../../" type="war"/>
    	
    </server>

Conclusion

 

In this article, we have shown how to develop and deploy an application that uses the SessionCache service in Bluemix. We hope that you found using the SessionCache service is easy and that it helps improve scalability and performance — and who doesn't want that?


RELATED TOPICS:SessionCache serviceWebSphere eXtreme Scale TrialScalability

Add a comment

Note: HTML elements are not supported within comments.


1000 characters left

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Cloud computing, WebSphere
ArticleID=970058
ArticleTitle=Improve scalability with the SessionCache service
publish-date=06302014