miércoles, 18 de diciembre de 2013

Ehcache Cache Search API Fundamentals

Introduction

In this entry I want to give out an excerpt of my book Instant Effective Caching with Ehcache. I have chosen the Ehcache Search API chapter so we can analyze a very simple example about its internals and a practical implementation. If you would like to purchase a copy of the book please follow the links:

EhCache search API allows us to query and search for elements that are already cached. This is achieved thanks to the ability to use indexing on keys and/or values pertaining to the object being cached. Ehcache provides queries that let us create arbitrary complex searches based on conditions, making this tool indispensable for professional caching.

To get the most of this tutorial download this book's recipe source code from github (or optionally clone the repository to get all the book's recipes source code) here:

How It Works
Ehcache provides a simple to use Search API that allows us to retrieve objects from cache layer based on conditions and other criteria. The implementation resembles that one of simple JDBC – SQL queries.

We start by editing the Ehcache configuration by adding the searchable directive. This tells Ehcache that for that particular cache we want it to be searchable.

We then define the Search Attributes. These are index mappings that tell Ehcache what attribute of your object you want to be searchable and a name to refer to it (always use “value” as your object reference).

Now, in our code we need to create a map to hold attributes (not strictly necessary but a good practice and convenient way to access the attributes in an ordered way).

Optionally, if your cache object layer is complex, you will want to implement a custom accessor that can help you to increase performance while lookups. This can be easily achieved by implementing the Ehcache AttributeExtractor interface and redefining the behavior you desire. The procedure is just like if you were defining an index in a SQL table.

You can find a fully working sample project in my github repository (please refer to the top of this entry for details on how to get it).