我試圖用Memcached設置Spring 3.1緩存解決方案。我已經成功地引入了ehcache(Spring已經爲此提供了支持)。然而,我堅持使用memcached的問題。我很抱歉提前的長度(這主要是樣板代碼)...Memcached + Spring緩存
我使用Java配置,所以我已經註釋了我的控制器配置以啓用緩存,如下所示。
@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
}
我使用MyBatis的,所以我創建了股票對象映射。然後將映射器注入到我的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);
}
}
下面是示例控制器,這是應該緩存顯示所有的股票(當加入一隻股票該高速緩存被完全逐出的結果,更新,或從數據庫中刪除):
@Controller
public class ListAllStocksController {
@Autowired
private TradingService tradingService;
@Cacheable("viewCache")
@RequestMapping(value = "listStocks.html", method = RequestMethod.GET)
public ModelAndView displayAllStocks() {
//The SerializableModelAndView extends Spring's ModelAndView and implements Serializable due to spymemcached not being able to add a non-serializable object to the cache
final ModelAndView mav = new SerializableModelAndView("listStocks");
mav.addObject("stocks", tradingService.getAll());
return mav;
}
@CacheEvict(value = "viewCache", allEntries = true)
@RequestMapping(value = "editStock.html", method = RequestMethod.POST, params = "submit=Edit")
public ModelAndView editStock(final Stock stock, final BindingResult result) {
final ModelAndView mav = new ModelAndView("redirect:listStocks.html");
tradingService.updateStock(stock);
return mav;
}
@CacheEvict(value = "viewCache", allEntries = true)
@RequestMapping(value = "listStocks.html", method = RequestMethod.POST, params = "submit=Delete")
public ModelAndView deleteStockAction(@RequestParam("name") final String name) {
final ModelAndView mav = new ModelAndView("redirect:listStocks.html");
tradingService.removeStock(stock);
return mav;
}
}
這是我小的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;
}
}
這裏是我的memcache類的樣子:
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();
}
}
我試過這與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 [[email protected]] was not registered for synchronization because synchronization is not active
58520 [qtp1656205248-16] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [[email protected]] will not be managed by Spring
58521 [qtp1656205248-16] DEBUG com.ehcache.reference.dao.StockMapper.findAll - ooo Using Connection [[email protected]]
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 [[email protected]]
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 [[email protected]] was not registered for synchronization because synchronization is not active
263038 [qtp1656205248-14] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [[email protected]] will not be managed by Spring
263038 [qtp1656205248-14] DEBUG com.ehcache.reference.dao.StockMapper.save - ooo Using Connection [[email protected]]
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 [[email protected]]
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 [[email protected]] was not registered for synchronization because synchronization is not active
263051 [qtp1656205248-18] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [[email protected]] will not be managed by Spring
263051 [qtp1656205248-18] DEBUG com.ehcache.reference.dao.StockMapper.findAll - ooo Using Connection [[email protected]]
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 [[email protected]]
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或spymemcached中的限制/錯誤還是我MemCache代碼中的一個錯誤?
您可以檢查每一步中存儲在memcached中的內容嗎?使用putty/telent連接到memcached服務器並檢查viewCache是否已更新。 – ragnor 2012-07-06 20:58:57
上面的日誌只顯示viewCache。我可以看到一個值被設置,但它不是正確的值。我猜是因爲擴展模型和視圖實現了可序列化,以及沒有正確序列化的東西。 – Scott 2012-07-09 12:58:18
你可以嘗試使用JSON序列化Simple Spring Memcached,這樣你就可以看到存儲在緩存中的究竟是什麼? – ragnor 2012-07-10 05:44:33