- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 Memcached 设置 Spring 3.1 缓存解决方案。我已经成功地合并了 ehcache(Spring 内置了对此的支持)。但是,我遇到了 memcached 的问题。我提前为长度道歉(它主要是样板代码)...
我使用的是 Java 配置,所以我注释了我的 Controller 配置以启用缓存,如下所示。
@Configuration @EnableWebMvc @EnableCaching
@ComponentScan("com.ehcache.reference.web")
public class ControllerConfig extends WebMvcConfigurerAdapter {
//Bean to create ViewResolver and add the Resource handler
}
这设置了三个 Controller ,允许对 Stock 元素执行基本的 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,所以我为 Stock 对象创建了一个 Mapper。然后将映射器注入(inject)到我的 DAO 中,然后将 DAO 注入(inject)到服务中。工作缓存(在两种实现中)出现在“服务”层中。下面是利用注入(inject)的 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 ,它应该缓存显示所有股票的结果(当从数据库中添加、更新或删除股票时,此缓存将被完全驱逐):
@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;
}
}
这是我的小缓存管理器:
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。这是我第一次启动应用程序并点击列表 Controller 时看到的日志记录:
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
这里不好玩的一点是,当我向系统添加股票时,我被重定向到 displayAllStocks 方法。它最初正确地执行此操作,但是如果我刷新页面,我会收到原始版本(显示没有库存的版本)。我被困在这里,不确定此时可能导致此问题的原因。如果我以任何方式使缓存无效,重定向将正常工作。在随后的刷新中,我检索到似乎是第一个输入的值(已删除)
这是配置问题吗? memcache 或 spymemcached 中的限制/错误,或者只是我的 MemCache 代码中的错误?
最佳答案
在 TradingServiceImpl 中,getStock 方法总是从缓存中返回相同的对象,而与股票名称无关。您应该将其更改为:
@Override
@Cacheable(value = "stockCache", key="#stockName")
public Stock getStock(final String stockName) {
return stockDao.findByName(stockName);
}
你在哪里驱逐viewCache?我在你的代码中没有看到它。
如果你想在 Spring 3.1 缓存抽象上使用 memcached,你可以选择 Simple-Spring-Memcached(当前快照版本 - 你需要从源代码构建它)。 Here您可以找到如何使用 SSM 将 memcached 与 Spring Cache 集成的示例配置。
示例项目:spring-cache-integration-test在 SSM svn 中可以使用此集成。
更新:Simple Spring Memcached 3.0.0 与 Spring Cache 集成已经可用。
关于java - 内存缓存+ Spring 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11364554/
我在具有 2CPU 和 3.75GB 内存 (https://aws.amazon.com/ec2/instance-types/) 的 c3.large Amazon EC2 ubuntu 机器上运
我想通过用户空间中的mmap-ing并将地址发送到内核空间从用户空间写入VGA内存(视频内存,而不是缓冲区),我将使用pfn remap将这些mmap-ed地址映射到vga内存(我将通过 lspci
在 Mathematica 中,如果你想让一个函数记住它的值,它在语法上是很轻松的。例如,这是标准示例 - 斐波那契: fib[1] = 1 fib[2] = 1 fib[n_]:= fib[n] =
我读到动态内存是在运行时在堆上分配的,而静态内存是在编译时在堆栈上分配的,因为编译器知道在编译时必须分配多少内存。 考虑以下代码: int n; cin>>n; int a[n]; 如果仅在运行期间读
我是 Python 的新手,但我之前还不知道这一点。我在 for 循环中有一个基本程序,它从站点请求数据并将其保存到文本文件但是当我检查我的任务管理器时,我发现内存使用量只增加了?长时间运行时,这对我
我正在设计一组数学函数并在 CPU 和 GPU(使用 CUDA)版本中实现它们。 其中一些函数基于查找表。大多数表占用 4KB,其中一些占用更多。基于查找表的函数接受一个输入,选择查找表的一两个条目,
读入一个文件,内存被动态分配给一个字符串,文件内容将被放置在这里。这是在函数内部完成的,字符串作为 char **str 传递。 使用 gdb 我发现在行 **(str+i) = fgetc(aFil
我需要证实一个理论。我正在学习 JSP/Java。 在查看了一个现有的应用程序(我没有写)之后,我注意到一些我认为导致我们的性能问题的东西。或者至少是其中的一部分。 它是这样工作的: 1)用户打开搜索
n我想使用memoization缓存某些昂贵操作的结果,这样就不会一遍又一遍地计算它们。 两个memoise和 R.cache适合我的需要。但是,我发现缓存在调用之间并不可靠。 这是一个演示我看到的问
我目前正在分析一些 javascript shell 代码。这是该脚本中的一行: function having() { memory = memory; setTimeout("F0
我有一种情况,我想一次查询数据库,然后再将整个数据缓存在内存中。 我得到了内存中 Elasticsearch 的建议,我用谷歌搜索了它是什么,以及如何在自己的 spring boot 应用程序中实现它
我正在研究 Project Euler (http://projecteuler.net/problem=14) 的第 14 题。我正在尝试使用内存功能,以便将给定数字的序列长度保存为部分结果。我正在
所以,我一直在做 Java 内存/注意力游戏作业。我还没有达到我想要的程度,它只完成了一半,但我确实让 GUI 大部分工作了......直到我尝试向我的框架添加单选按钮。我认为问题可能是因为我将 JF
我一直在尝试使用 Flask-Cache 的 memoize 功能来仅返回 statusTS() 的缓存结果,除非在另一个请求中满足特定条件,然后删除缓存。 但它并没有被删除,并且 Jinja 模板仍
我对如何使用 & 运算符来减少内存感到非常困惑。 我可以回答下面的问题吗? clase C{ function B(&$a){ $this->a = &$a; $thi
在编写代码时,我遇到了一个有趣的问题。 我有一个 PersonPOJO,其 name 作为其 String 成员之一及其 getter 和 setter class PersonPOJO { priv
在此代码中 public class Base { int length, breadth, height; Base(int l, int b, int h) { l
Definition Structure padding is the process of aligning data members of the structure in accordance
在 JavaScript Ninja 的 secret 中,作者提出了以下方案,用于在没有闭包的情况下内存函数结果。他们通过利用函数是对象这一事实并在函数上定义一个属性来存储过去调用函数的结果来实现这
我正在尝试找出 map 消耗的 RAM 量。所以,我做了以下事情;- Map cr = crPair.collectAsMap(); // 200+ entries System.out.printl
我是一名优秀的程序员,十分优秀!