Java Memcached+Spring缓存
我正在尝试使用Memcached设置Spring3.1缓存解决方案。我已经成功地将ehcache Spring内置的对这一点的支持合并到一起。然而,我被memcached的一个问题困住了。我很抱歉提前这么长时间,大部分都是样板代码 我使用的是Java配置,因此我对控制器配置进行了注释,以启用缓存,如下所示Java Memcached+Spring缓存,java,spring,caching,memcached,spymemcached,Java,Spring,Caching,Memcached,Spymemcached,我正在尝试使用Memcached设置Spring3.1缓存解决方案。我已经成功地将ehcache Spring内置的对这一点的支持合并到一起。然而,我被memcached的一个问题困住了。我很抱歉提前这么长时间,大部分都是样板代码 我使用的是Java配置,因此我对控制器配置进行了注释,以启用缓存,如下所示 @Configuration @EnableWebMvc @EnableCaching @ComponentScan("com.ehcache.reference.web") publi
@Configuration @EnableWebMvc @EnableCaching
@ComponentScan("com.ehcache.reference.web")
public class ControllerConfig extends WebMvcConfigurerAdapter {
//Bean to create ViewResolver and add the Resource handler
}
这将设置三个控制器,允许对库存元素执行基本CRUD操作。业务对象看起来像:
public class Stock implements Serializable {
private String name;
private double cost; //This isn't a real app, don't care about correctness of value
//Getters, Setters contructors, etc... left out just a standard POJO
public class MemCache implements Cache {
private MemcachedClient cache;
private final String name;
private static final Logger LOGGER = Logger.getLogger(MemCache.class);
public MemCache(final String name, final int port) throws URISyntaxException {
this.name = name;
try {
cache = new MemcachedClient(AddrUtil.getAddresses("localhost:" + port));
final SerializingTranscoder stc = (SerializingTranscoder) cache.getTranscoder();
stc.setCompressionThreshold(600000);
} catch (final IOException e) { //Let it attempt to reconnect }
}
@Override
public String getName() {
return name;
}
@Override
public Object getNativeCache() {
return cache;
}
@Override
public ValueWrapper get(final Object key) {
Object value = null;
try {
value = cache.get(key.toString());
} catch (final Exception e) {
LOGGER.warn(e);
}
if (value == null) {
return null;
}
return new SimpleValueWrapper(value);
}
@Override
public void put(final Object key, final Object value) {
cache.set(key.toString(), 7 * 24 * 3600, value);
Assert.assertNotNull(get(key)); //This fails on the viewCache
}
@Override
public void evict(final Object key) {
this.cache.delete(key.toString());
}
@Override
public void clear() {
cache.flush();
}
}
}
我正在使用MyBatis,因此我为Stock对象创建了一个映射器。映射器然后被注入到我的DAO中,DAO随后被注入到服务中。两种实现中的工作缓存都发生在服务层。下面是使用注入的DAO的服务层:
public class TradingServiceImpl implements TradingService {
@Autowired
private final StockDao stockDao;
public TradingServiceImpl(final StockDao stockDao) {
this.stockDao = stockDao;
}
@Override
public void addNewStock(final Stock stock) {
stockDao.save(stock);
}
@Override
@Cacheable(value = "stockCache")
public Stock getStock(final String stockName) {
return stockDao.findByName(stockName);
}
@Override
public List<Stock> getAll() {
return stockDao.findAll();
}
@Override
@CacheEvict(value = "stockCache", key = "#stock.name")
public void removeStock(final Stock stock) {
stockDao.delete(stock);
}
@Override
@CacheEvict(value = "stockCache", key = "#stock.name")
public void updateStock(final Stock stock) {
stockDao.update(stock);
}
}
这是我的小型CacheManager:
public class MemCacheManager extends AbstractCacheManager {
private final Collection<MemCache> internalCaches;
public MemCacheManager(final Collection<MemCache> internalCaches) {
this.internalCaches = internalCaches;
}
@Override
protected Collection<? extends Cache> loadCaches() {
Assert.notNull(internalCaches, "A collection caches is required and cannot be empty");
return internalCaches;
}
}
我用CouchBase和普通memcached都试过了。下面的设置显示memcached仅由自身启动
@Configuration @EnableCaching @Profile("memcached")
public class MemCacheConfiguration implements CachingConfigurer {
@Override @Bean
public CacheManager cacheManager() {
CacheManager cacheManager;
try {
cacheManager = new MemCacheManager(internalCaches());
return cacheManager;
} catch (final URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Bean
public Collection<MemCache> internalCaches() throws URISyntaxException {
final Collection<MemCache> caches = new ArrayList<MemCache>();
// caches.add(new MemCache("stockCache", 11212));
caches.add(new MemCache("viewCache", 11211));
return caches;
}
@Override
public KeyGenerator keyGenerator() {
return new DefaultKeyGenerator();
}
}
在上面的例子中,我们只是使用memcached。以下是我第一次启动应用程序并点击列表控制器时看到的日志:
58513 [qtp1656205248-16] TRACE org.springframework.cache.interceptor.CacheInterceptor - Computed cache key 0 for operation CacheableOperation[public org.springframework.web.servlet.ModelAndView com.ehcache.reference.web.ListAllStocksController.displayAllStocks()] caches=[viewCache] | condition='' | key='0'
58519 [qtp1656205248-16] WARN com.memcache.MemCache - Retrieved: null from the cache 'viewCache' at <0> key of type <java.lang.Integer>
58519 [qtp1656205248-16] ERROR com.memcache.MemCache - Returning null
58520 [qtp1656205248-16] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
58520 [qtp1656205248-16] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@640f434f] was not registered for synchronization because synchronization is not active
58520 [qtp1656205248-16] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [org.hsqldb.jdbc.JDBCConnection@260c2adb] will not be managed by Spring
58521 [qtp1656205248-16] DEBUG com.ehcache.reference.dao.StockMapper.findAll - ooo Using Connection [org.hsqldb.jdbc.JDBCConnection@260c2adb]
58521 [qtp1656205248-16] DEBUG com.ehcache.reference.dao.StockMapper.findAll - ==> Preparing: SELECT * from STOCK
58521 [qtp1656205248-16] DEBUG com.ehcache.reference.dao.StockMapper.findAll - ==> Parameters:
58521 [qtp1656205248-16] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@640f434f]
58521 [qtp1656205248-16] WARN com.memcache.MemCache - Setting: ModelAndView: reference to view with name 'listStocks'; model is {stocks=[]} into the cache 'viewCache' at <0> key of type <java.lang.Integer>
58527 [qtp1656205248-16] WARN com.memcache.MemCache - Retrieved: ModelAndView: materialized View is [null]; model is null from the cache 'viewCache' at <0> key of type <java.lang.Integer>
这一切看起来都是正确的,这是一个新的启动缓存中应该没有任何内容。现在,我将向缓存中添加股票:
263036 [qtp1656205248-14] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
263036 [qtp1656205248-14] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3d20b8d5] was not registered for synchronization because synchronization is not active
263038 [qtp1656205248-14] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [org.hsqldb.jdbc.JDBCConnection@40b5f9bb] will not be managed by Spring
263038 [qtp1656205248-14] DEBUG com.ehcache.reference.dao.StockMapper.save - ooo Using Connection [org.hsqldb.jdbc.JDBCConnection@40b5f9bb]
263038 [qtp1656205248-14] DEBUG com.ehcache.reference.dao.StockMapper.save - ==> Preparing: INSERT INTO STOCK (name, cost) VALUES (?, ?)
263039 [qtp1656205248-14] DEBUG com.ehcache.reference.dao.StockMapper.save - ==> Parameters: A(String), 1.0(Double)
263039 [qtp1656205248-14] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3d20b8d5]
263039 [qtp1656205248-14] TRACE org.springframework.cache.interceptor.CacheInterceptor - Invalidating cache key 0 for operation CacheEvictOperation[public org.springframework.web.servlet.ModelAndView com.ehcache.reference.web.AddStockController.addNewStock(com.ehcache.reference.business.Stock,org.springframework.validation.BindingResult)] caches=[viewCache] | condition='' | key='0',false,false on method public org.springframework.web.servlet.ModelAndView com.ehcache.reference.web.AddStockController.addNewStock(com.ehcache.reference.business.Stock,org.springframework.validation.BindingResult)
263039 [qtp1656205248-14] WARN com.memcache.MemCache - Evicting value at <0> in cache 'viewCache'
263049 [qtp1656205248-18] TRACE org.springframework.cache.interceptor.CacheInterceptor - Computed cache key 0 for operation CacheableOperation[public org.springframework.web.servlet.ModelAndView com.ehcache.reference.web.ListAllStocksController.displayAllStocks()] caches=[viewCache] | condition='' | key='0'
263051 [qtp1656205248-18] WARN com.memcache.MemCache - Retrieved: null from the cache 'viewCache' at <0> key of type <java.lang.Integer>
263051 [qtp1656205248-18] ERROR com.memcache.MemCache - Returning null
263051 [qtp1656205248-18] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
263051 [qtp1656205248-18] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7050d0a7] was not registered for synchronization because synchronization is not active
263051 [qtp1656205248-18] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [org.hsqldb.jdbc.JDBCConnection@49b2bd8c] will not be managed by Spring
263051 [qtp1656205248-18] DEBUG com.ehcache.reference.dao.StockMapper.findAll - ooo Using Connection [org.hsqldb.jdbc.JDBCConnection@49b2bd8c]
263051 [qtp1656205248-18] DEBUG com.ehcache.reference.dao.StockMapper.findAll - ==> Preparing: SELECT * from STOCK
263052 [qtp1656205248-18] DEBUG com.ehcache.reference.dao.StockMapper.findAll - ==> Parameters:
263053 [qtp1656205248-18] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7050d0a7]
263053 [qtp1656205248-18] WARN com.memcache.MemCache - Setting: ModelAndView: reference to view with name 'listStocks'; model is {stocks=[Stock Name: <A> Current Cost <1.0>]} into the cache 'viewCache' at <0> key of type <java.lang.Integer>
263055 [qtp1656205248-18] WARN com.memcache.MemCache - Retrieved: ModelAndView: materialized View is [null]; model is null from the cache 'viewCache' at <0> key of type <java.lang.Integer>
减去最后一行,这一切看起来都是正确的。这是我从memcached-vv的输出:
<156 get 0 ##Initial listing of all
>156 END
<156 set 0 1 604800 79 ##Cache initial result on startup
>156 STORED
<156 get 0
>156 sending key 0
>156 END
<156 delete 0 ##Invalidation when stock added
>156 DELETED
<156 get 0 ##Add redirects to the get page
>156 END
<156 set 0 1 604800 79 ##Store the new value
>156 STORED
<156 get 0
>156 sending key 0 ##Refresh the page
>156 END
这里的unfun位是当我向系统添加股票时,我被重定向到displayAllStocks方法。它最初这样做是正确的,但是如果我刷新页面,我会被发送到原始版本,即不显示库存的版本。我被困在这里,不确定是什么导致了这个问题。如果我以任何方式使缓存无效,重定向将正常工作。在随后的刷新中,我检索到的似乎是第一个被删除的值
这是配置问题吗?memcache或SpymeMached中的限制/错误,或者只是我的memcache代码中的错误?在TradingServiceImpl中,getStock方法始终从缓存返回相同的对象,而不依赖于股票名称。您应该将其更改为:
@Override
@Cacheable(value = "stockCache", key="#stockName")
public Stock getStock(final String stockName) {
return stockDao.findByName(stockName);
}
在哪里逐出viewCache?我在你的代码里没看到
如果您想在Spring3.1缓存抽象上使用memcached,您可以使用简单的SpringMemcached当前快照版本—您需要从源代码构建它。您可以找到如何使用SSM将memcached与Spring Cache集成的示例配置。
示例项目:SSM svn中提供了使用此集成的功能
更新:3.0.0与Spring Cache集成已经可用。您可以检查每个步骤中memcached中存储的内容吗?使用putty/telent连接到memcached服务器,并检查viewCache是否已更新。上面的日志仅显示viewCache。我可以看到设置了一个值,但它不是正确的值。我猜是因为扩展模型和视图实现了serializable,而有些东西没有被正确序列化。您可以尝试简单的Spring Memcached和JSON序列化,这样您就可以看到缓存中到底存储了什么?
@Override
@Cacheable(value = "stockCache", key="#stockName")
public Stock getStock(final String stockName) {
return stockDao.findByName(stockName);
}