tisdag 22 januari 2008

NHibernate: Enable second level cache using MemCached

The second level cache is a powerful feature used by NHibernate to cache objects and queries to limit the number of database queries.

NHibernate uses a provider based architecture where cache providers can be plugged in using the config file.

NHibernate is shipped with several cache providers, example:
- SysCache (uses ASP.NET Cache Objects to cache data)
- MemCached (distributed in-memory Cache running as a separate Windows Service)

We will use MemCached in this example.

There are several win32 ports of MemCached available. We will use one available at:
http://jehiah.cz/projects/memcached-win32/

Start by downloading MemCached from the URL above and from a Command prompt type:
memcached -d install <enter>
memcached -d start <enter>

This will start the MemCached service on your computer.

Next, we will configure MemCached in your application. Add a new configuration settings in your config file under <configSettings>:
<section name="memcache" type="NHibernate.Caches.MemCache.MemCacheSectionHandler,NHibernate.Caches.MemCache" />

Add the MemCached settings using:
<memcache>
<memcached host="192.168.1.0" port="11211" weight="1"/>
</memcache>

The next step is to enable caching in your NHiberate project. Under the <NHibernate> node, add the following application settings:
<add key="hibernate.cache.provider_class" value="NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache" />
<add key="hibernate.cache.use_query_cache" value="true"/>
<add key="expiration" value="120" />


At last we need to enable caching for the persistant classes in your application. This is done in the hbm.xml file using the <cache> element:
<class name="NameSpace.Class, NameSpace" table="tblInDb">
<cache usage="read-write"/>
...
</class>


To enable caching for relations, add the <cache> element for each relation:
<bag name="Childs" lazy="true">
<cache usage="read-write"/>
<key column="ParentId"/>
<one-to-many class="NameSpace.ChildClass, NameSpace"/>
</bag>



The second level cache is used by NHibernate in the following scenarios:
- Single objects retrieved using ISession.Load
- Lists of objects retrieved using IQuery.List (if hibernate.cache.use_query_cache is set to true)
- Relational objects (when the bag is marked with <cache>)

Note that NHibernate does not use the second level cache when using ICriteria.

1 kommentar:

William sa...

another option is to use NCache as a N L2 cache providerfor NHibernate.