Friday, May 11, 2012

Memcached Spring integration

This is very simple example showing how to integrate Spring with memcached.

MemcachedClientFactoryBean is a Spring factory, which creates instance of MemcachedClient. Client class manages connections to memcached server farm, and takes care of .... mostly everything that is required for daily usage ;)

Configured Transcoder serializes Java objects - they are available on memcached server in binary form.

Spring bean below has single injection -  "memcached.client", this is the bean name of the factory, but spring recognises, that injected bean is a factory and does not inject factory itself, but uses it to create Bean instance - in this case memcached client.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="memcached.client" class="net.spy.memcached.spring.MemcachedClientFactoryBean">
        <property name="servers" value="host1:1122,host2:1122" />
        <property name="protocol" value="BINARY" />
        <property name="transcoder">
            <bean class="net.spy.memcached.transcoders.SerializingTranscoder" />
        </property>
        <property name="locatorType" value="ARRAY_MOD" />
        <property name="opTimeout" value="2000" />
        <property name="failureMode" value="Cancel" />
        <property name="useNagleAlgorithm" value="false" />
        <property name="timeoutExceptionThreshold" value="20" />
    </bean>
</beans> 
@Named
public class MemcachedSpringBeanExample {

    private MemcachedClient memcached;

    @Inject
    protected MemcachedSpringBeanExample(@Named("memcached.client") MemcachedClient memcached) {
        this.memcached = memcached;
    }

    public void doSomething(UasAccountId uasAccountId, LastLoginHistory histiry) {
        memcached.add("my_bean_key", 2000, new Object[] { "val1", "val2" });
    }
}

2 comments:

  1. Hi Mac,
    I am very for this but i have some problem with memcache,I am trying for this in spring and hibernate with memcache but we are facing the problem if u have any idea about the configuration please reply as soon as possible(example program).


    Thanks & Regards,
    Rajasekhar

    ReplyDelete