Spring cache using memcached

不想你离开。 提交于 2020-01-05 07:31:09

问题


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:


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.



来源:https://stackoverflow.com/questions/26978823/spring-cache-using-memcached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!