2

我正在使用https://github.com/AKQABER/simple-spring-memcached将 memcached 集成为 spring 的缓存实现。

但我没有成功:P

我正在使用 spring 4 和 spring-data-jpa

public interface FooRepository extends JpaRepository<Foo, Long> {

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

我为测试目的对密钥进行了硬编码。没什么特别的,使用名为“defaultCache”的缓存。memcached的配置是:

@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;
}
}

我可以使用带有代码的简单主类对其进行测试:

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");

并且 obj 始终为空。但是,如果我直接使用 defaultCache 对象,我可以毫无问题地将项目放入/从缓存中获取。任何的想法?

4

1 回答 1

4

您是否在应用程序中启用了 Spring Cache?如果没有,则@EnableCaching在配置 bean 上使用。

如果您使用org.springframework.cache.support.SimpleCacheManager而不是SSMCacheManager. 如果不是,那么 Spring Cache 配置仍然存在问题。

于 2014-11-17T20:45:25.053 回答