Spring cache using memcached

7.2k views Asked by At

I'm using https://github.com/AKQABER/simple-spring-memcached to have memcached integrated as a cache implementation with spring.

But I'had no success :P

I'm using spring 4 and spring-data-jpa

public interface FooRepository extends JpaRepository<Foo, Long> {

@Cacheable(value = "defaultCache", key = "lala")
    Foo findByNameAndDescription(String name, String description);
} 

I hardcoded the key for test purposes. Nothing special, use a cache called "defaultCache". The configuration of memcached is:

@Configuration
@EnableAspectJAutoProxy
public class CacheConfiguration
{

@Bean
public CacheManager cacheManager()
{
    MemcacheClientFactoryImpl cacheClientFactory = new MemcacheClientFactoryImpl();
    AddressProvider addressProvider = new DefaultAddressProvider("127.0.0.1:11211");
    com.google.code.ssm.providers.CacheConfiguration cacheConfiguration = new com.google.code.ssm.providers.CacheConfiguration();
    cacheConfiguration.setConsistentHashing(true); //TODO check this

    CacheFactory cacheFactory = new CacheFactory();
    cacheFactory.setCacheName           ( "defaultCache"        );
    cacheFactory.setCacheClientFactory  ( cacheClientFactory    );
    cacheFactory.setAddressProvider     ( addressProvider       );
    cacheFactory.setConfiguration       ( cacheConfiguration    );

    Cache object = null;
    try {
        object = cacheFactory.getObject();
    } catch (Exception e) {
        e.printStackTrace();
    }

    SSMCache ssmCache = new SSMCache(object, 10000, true); //TODO be very carefully here, third param allow remove all entries!!

    ArrayList<SSMCache> ssmCaches = new ArrayList<SSMCache>();
    ssmCaches.add(0, ssmCache);

    SSMCacheManager ssmCacheManager = new SSMCacheManager();
    ssmCacheManager.setCaches(ssmCaches);


    return ssmCacheManager;
}
}

And I can test it using a simple main class with code:

CacheManager cacheManager = context.getBean(CacheManager.class);
    FooRepository repository = context.getBean(FooRepository.class);

    Cache defaultCache = cacheManager.getCache("defaultCache");
    defaultCache.clear();
    Foo byNameAndDescription = repository.findByNameAndDescription(DEFAULT_NAME,    DEFAULT_DESCRIPTION);
    Object obj = defaultCache.get("lala");

And obj is always null. However if I use defaultCache object directly I can put and get items to/from cache without problems. Any idea?

1

There are 1 answers

1
ragnor On BEST ANSWER

Have you enabled Spring Cache in you application? If not then use @EnableCaching on the configuration bean.

If it doesn't help check if the caching work if you use org.springframework.cache.support.SimpleCacheManager instead of SSMCacheManager. If not then there is still a problem with Spring Cache configuration.