我正在使用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对象,我可以放置和从缓存中获取项目而不会出现问题。有什么想法吗?
答案 0 :(得分:4)
您是否在应用程序中启用了Spring Cache?如果没有,那么在配置bean上使用@EnableCaching
。
如果使用org.springframework.cache.support.SimpleCacheManager
代替SSMCacheManager
,则无法检查缓存是否有效。如果没有,那么Spring Cache配置仍然存在问题。