Using DynaCache to improve the performance of your WebSphere Process Server or WebSphere ESB solution

When developing SCA solutions, you frequently require data that is expensive to fetch or compute. To obtain this information, you may invoke a Web service, connect to a database, perform complex logic, or aggregate data from multiple sources. If this data does not change over time, you can often achieve significant performance gains with appropriate use of caching. This tutorial shows you a simple and effective caching technique, based on a mature product feature, DynaCache, that will help you meet application performance requirements. Additionally, by using DynaCache, the complexities of cache data replication and synchronization between nodes in a network deployment topology are automatically and transparently taken care of by the infrastructure.

Gabriel Telerman (g.telerman@uk.ibm.com), Senior IT Specialist, IBM

Author photoGabriel Telerman is a Senior IT Specialist with IBM Software Services for WebSphere in the United Kingdom. He has a degree in Computer Studies from Glasgow Caledonian University, United Kingdom, and ten years of experience with IBM. His areas of expertise include object-oriented programming, Enterprise Java, Web development, Web services, service-oriented architecture, and Enterprise Application Integration. Gabriel is an ITSO author of IBM Redbook: Getting Started with WebSphere Enterprise Service Bus, IBM Redbook workshop: Building WebSphere ESB Solutions, and a Contributing Author for developerWorks.



02 December 2009

Also available in Chinese

About this tutorial

This tutorial is based on a fictional service that retrieves and returns location details. You can imagine this service as being part of a room booking system, for which information about a campus and its facilities is fetched from an external entity. You are confident that campus facility information will rarely change, so you consider this particular service as a strong candidate for local caching. When a change in location details data occurs, you will also learn how to invalidate cache entries and clear the cache.

Objectives

You will learn how to:

Prerequisites

This tutorial assumes you have an intermediate understating of the Java™ programming language, some familiarity with the SCA programming model, and you are reasonably comfortable working with WSDL interfaces, data types, SCA components, and the Integration Test Client in WebSphere® Integration Developer.

System requirements

This material was developed using WebSphere Integration Developer V6.2.0.2. However, the code will compile and run on all versions of the product, including the forthcoming Version 7.

Duration

This tutorial takes about 1 hour to complete.


Defining the service interface

In this section, you will prepare the interface and data types required to access the service.

Task 1: Create the WebSphere Integration Developer project

  1. Launch WebSphere Integration Developer with a new workspace and go to the Business Integration perspective.
  2. Use the File -> New -> Module menu, name the module CachingTutorial, leave all defaults, and click Finish.

Task 2: Create the service interface and message types

  1. You will be using four data types to represent request and response messages:
    • LocationBasicInfo
    • Address
    • Facility
    • LocationDetails
  2. Create a new Data Type by right-clicking the Data Types folder in the Business Integration view and selecting New -> Business Object.
  3. Name the new business object LocationBasicInfo. This data type represents the request message and contains the location ID used as a key for retrieving location details.
  4. Add two string attributes to the object named id and name. Use the Add Field tool to add attributes, as shown in Figure 1.
    Figure 1. Request message
    Request message
  5. Next, create the remaining three business objects, which are combined together to build the response data structure. Pay particular attention to the "Facilities" field on LocationDetails, which is an array of objects of the type Facility (Figure 2).
    Figure 2. Response message
    Response message
  6. Finally, create the service interface. You can do this by right-clicking the Interfaces folder. Name the interface LocationService, create a request-response operation named retrieveLocationDetails, with an input parameter called request of type LocationBasicInfo, and an output parameter called response of type LocationDetails (Figure 3).
    Figure 3. Service interface
    Service interface
    You now have a definition of the request and response data structures and a description of the service interface and its operation.

    I have been deliberate with the structure of the response message, LocationDetails. Response objects will be ultimately stored in the cache, and I wanted to exhibit the ability of our caching solution to deal with a variety of data structures. If you revisit Figure 2, you will see that the response object includes a simple type (name of type string), a complex type (address of type Address) and a sequence (facilities array of objects of type Facility).

Building the caching component

In this section, you learn how to build a transparent cache by creating a Java component that implements the same interface as the target service and interacts with the WebSphere Dynamic cache service.

  1. Open the Assembly Diagram by double-clicking it in the Business Integration view. You can inspect the business objects and interface you just created. They are present in the Business Integration view as shown in Figure 4.
    Figure 4. Business Integration view
    Business Integration view
  2. Create a Java component in the Assembly Diagram. Name this component CachingComponent and use its pop-up toolbar to add an interface and a reference to the component. Use the LocationService interface for both. Save the assembly diagram. Refer to Figure 5 for the complete assembly.
    Figure 5. Complete assembly
    Complete assembly
    For this tutorial, the assembly is now complete and provides a working module for you to test. In practice, the target service resides elsewhere and you are binding to it using an Import. You may also mediate requests and responses using a mediation component before using an Export to expose the service to your consumers.

    In such an arrangement, your consumers will bind to your module export. The insertion of the caching component between the export and the mediation component is completely transparent to the service consumers.
  3. Double-click the caching component to generate its implementation. A stub method is generated for the retrieveLocationDetails operation, which you will shortly implement.
  4. Before implementing the interface operation, you need to create a static class member and static method to lookup the default DynaCache object cache instance (Listing 1).
    Listing 1. Default object cache instance
    private static DistributedObjectCache cache = initCache();
    static DistributedObjectCache initCache(){
      try {
        InitialContext ic = new InitialContext();
        return (DistributedObjectCache) ic.lookup("services/cache/distributedmap");
      } catch (NamingException e) {
        e.printStackTrace();
        return null;
      }
    }
  5. Add the imports in Listing 2 to the class.
    Listing 2. Caching component imports
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import com.ibm.websphere.cache.DistributedObjectCache;
  6. Now that you have a reference to a DynaCache object cache instance, you must implement the interface operation as shown in Listing 3.
    Listing 3, Interface operation implementation
    public DataObject retrieveLocationDetails(DataObject request) {
    
    // retrieve key to cache from the request
    String key = request.getString("id");
    	
    DataObject responseObject = null;
    
    // get response from cache
    responseObject = cache == null ? null : (DataObject) cache.get(key);
    
    // if cache miss invoke service and update cache
    if (responseObject == null) {
    	DataObject responseMessage = (DataObject)
    locateService_LocationServicePartner().invoke("retrieveLocationDetails", request);
    responseObject = responseMessage == null ? null :
    responseMessage.getDataObject("response");
    
    	if ((cache != null) && (responseObject != null)) {
    		cache.put(key, responseObject);
    	}
    }
    return responseObject;

    Take some time now to understand this code. WebSphere Application Server, upon which WebSphere Process Server and WebSphere ESB runtimes are built, provides a distributed caching infrastructure and API.

    A default object cache instance is always present and can be looked up using the JNDI name services/cache/distributedmap. Using this instance will be fine for the purpose of this tutorial, but in production systems, it is best practice to create a dedicated one for each service from which you want to cache responses. This ensures cache instance isolation and provides finer granularity for invalidating cache entries and clearing the cache. Go to the Resources section for further information about working with object cache instances and the WebSphere caching API.

    The interface method retrieves the id attribute from the request. This is then used as a key to retrieve the response from the cache. If no corresponding response is found, the code then invokes the service partner.
  7. Save and close the Java editor.

Testing the caching component

In this section, you deploy the module to the test server and verify that the service cache behaves as expected.

  1. On the assembly diagram, right-click the CachingComponent and select Test Component.
  2. In the Initial Request Parameters panel, populate the request ID and continue the test, confirming your deployment location. At this point, your test server will start and your module will be deployed automatically.
  3. The test client provides a manual emulator for the component reference. When the reference is invoked, you will be required to manually emulate the service. Go the Output Parameters section of the emulator and enter the response values, including some elements in the list of facilities and continue the test.
  4. Once the test completes, note the Events panel (Figure 6), which shows the emulation of the service.
    Figure 6. First run - response from service
    First run
  5. Rerun the test using the same request ID. This time, the emulator will not execute. Look at the events again as displayed in Figure 7. Note how the caching component no longer needs to invoke its service partner because it now finds a cached response associated with the request ID in DynaCache.
    Figure 7. Second run - response from cache
    Second run
  6. Finally, run the test a third time, but with a different request ID. This time, the reference emulator runs again and you need to supply new response values. Figure 8 shows the events panel after the third execution.
    Figure 8. Third run - response from service
    Third run

Working with cache entries and clearing the cache

Supplied with the product as part of the installable applications, there is a cache monitor application. This cache monitor is designed to monitor servlet cache instances. To monitor object cache instances, you need to extend this application as described in IBM Extended Cache Monitor for IBM WebSphere Application Server technology preview.

Once installed and updated, you can access the cache monitor from a Web browser, typically using the URL http://localhost:9080/cachemonitor/. Your actual port number may differ.

The cache monitor will use the same authentication credentials as the administrative console, typically "admin/admin" for a default WebSphere Integration Developer installation.

  1. Select the default cache instance from the drop-down list and click OK. You may need to click Refresh Instances before the default instance is present (Figure 9).

    Note: The default cache instance will only be created once a test executes. Make sure you have completed the Testing the caching component section before using the cache monitor.
    Figure 9. Default cache instance
    Default cache instance
  2. Click Cache Statistics and study the table in Figure 10. You will see that there are two used entries in the cache. One of the requests has been serviced by the cache and two requests were not satisfied by cached responses. Also note of the Clear Cache button, which is one of the ways that you can clear the cache. You can also clear the cache by restarting the server, or programmatically, by using the clear() method as described in the DistributedObjectCache API.
    Figure 10. Cache statistics
    Cache statistics
  3. Finally, click Cache Contents. In this panel (Figure 11), you see the two cache entries with the IDs used in the requests. You can invalidate individual cache entries from the cache contents panel.
    Figure 11. Cache contents
    Cache contents

There is also a rich set of parameters and policies that can be applied to cache instances to control attributes, such as the cache size, cache entry eviction criteria, enable cache entry offload to secondary storage, interdependencies between cache entries, cache entry timeouts, and many others.

For comprehensive information about managing the cache, refer to Using object cache instances.


Conclusion

In this tutorial, you learned how to use the WebSphere Dynamic Cache service from an SOA perspective. You identified a candidate service for which responses are cached to improve the performance of your solution and you learned how to build a transparent SCA caching component using WebSphere Integration Developer. You also tested the caching component and how to monitor and administer the cache. In addition, the tutorial discussed best practices for working with object cache instances.


Download

DescriptionNameSize
WID Project Interchange fileSCACachingTutorialPI.zip10KB

Resources

Comments

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.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere, SOA and web services
ArticleID=451317
ArticleTitle=Using DynaCache to improve the performance of your WebSphere Process Server or WebSphere ESB solution
publish-date=12022009