10

I have the Membase server installed with a couple buckets setup and I was looking for a good tutorial or example of how to use this as the 2nd level cache with NHibernate.

I am interested in what a sample configuration would look like and if there is anything I need to do in code or if I can handle it all from my NHibernate mappings.

Thanks for any assistance.

Brandon
  • 10,744
  • 18
  • 64
  • 97

1 Answers1

14

In your mapping files, you will need to include the property:

<class name="ClassName" table="Table">
   <cache usage="read-write" />
   <!-- SNIP -->
</class>

Options are read-write (read committed isolation), nonstrict-read-write (objects that are rarely written, better performance but increased chance of stale data), or read-only (data that never changes).

Then, in your web (or app) config you need a section to configure memcached:

<configuration>
  <configSections>
    <!-- SNIP -->
    <section name="memcache" type="NHibernate.Caches.MemCache.MemCacheSectionHandler,NHibernate.Caches.MemCache" />
  </configSections>
  <memcache>
    <memcached host="127.0.0.1" port="11211" weight="2" />
  </memcache>
  <!-- SNIP -->
</configuration>

Finally, in your session factory configuration be sure to use:

  <hibernate-configuration>
    <session-factory>
      <!-- SNIP -->

      <property name="expiration">300</property> <!--memcache uses seconds -->
      <property name="cache.provider_class">NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache</property>
      <property name="cache.use_second_level_cache">true</property>
      <property name="cache.use_query_cache">false</property> <!-- true if you want to cache query results -->
    </session-factory>
  </hibernate-configuration>

Of course you will need to download and reference a dll from the appropriate version of NHibernate.Caches to get the right cache provider. The memcached one takes a dependency on ICSharpCode.SharpZipLib and Memcached.ClientLibrary as well (s/b included in the download)

If you're using fluent NHibernate, there is a .Cache method in the setup chain for a session factory that you can use, though some of the properties need to be set manually through a call to .ExposeConfiguration.

AlexCuse
  • 18,008
  • 5
  • 42
  • 51
  • I found this example incomplete. First, you must install the Memcached server somewhere (if you want to install as a service on a Windows box, see part of the instructions on http://xrigher.info/php/how-to-install-memcache-on-windows-7-x64-with-wamp/). When adding the Memcached client binaries, I found that the binaries for 3.2 have a dependency on log4net.dll, so I had to copy that along with the Memcached client binaries. Also, adding the expiration key generates an error in my project – Mario Apr 11 '12 at 19:33
  • How can I install memcache for Windows Azure VM – Manjay_TBAG Jun 05 '19 at 06:19