我正在使用cache2k作为我的java应用程序的缓存。
如果缓存不在in缓存中,我将使用CacheSource来获取和查看请求。但是现在我想实现put方法。
希望有人能帮我。
private static Cache<String, Integer> c =
CacheBuilder.newCache(String.class, Integer.class)
.source(new CacheSource<String, Integer>() {
public Integer get(String o) {
System.out.println("ACCESSING SOURCE");
return checkCache(o) ? 1: 0; // checkCache checks if the item is in MySQL Cache
}
})
.name("cache")
.build();发布于 2014-11-01 07:19:15
对于第一个问题,您需要添加两行:
private static Cache<String, Integer> c =
CacheBuilder.newCache(String.class, Integer.class)
.name("cache")
.maxSize(1000) // limits in memory cache to 1000 entries
.expirySecs(60) // sets expiry (time to live) to 60 seconds
.source(new CacheSource<String, Integer>() {
public Integer get(String o) {
System.out.println("ACCESSING SOURCE");
return checkCache(o) ? 1: 0;
}
})
.build();关于expirySecs的两个提示:默认情况下,cache2k的默认到期时间为10分钟。您可以使用expirySecs(-1)关闭过期。即将发布的cache2k版本0.20将清理界面:eternal(true)将关闭过期。expiryDuration(long, Timeunit)是设置失效时间的新方法。expiryMillis和expirySecs方法仍然存在并受到支持,但将在以后的版本中消失。
第二个问题:要使用附带的mysql持久性将条目放入缓存中,请使用以下模式:
start database transaction
update item in the database
cache.remove(item key)
commit the transaction通过get()进行的下一个缓存访问将失败,调用缓存源并从数据库中获取更新的元素。如果get()发生在remove()和数据库提交之间,那么它将暂停,直到事务被提交(这实际上取决于您的remove()设置和事务隔离级别)。如果希望将cache2k用作数据库持久层的缓存,则此模式也有效。
使用cache.put,然后将元素插入数据库,会导致并发问题,因为这两个操作不是原子操作。上面的模式更安全,但速度更慢,因为每个缓存更新都需要一个数据库存储和获取。
另一个提示是:“最好的方式”将在未来改变。目前,我正在向cache2k添加一般的持久性支持。因此,这只是将来添加数据库属性的问题。
https://stackoverflow.com/questions/26683815
复制相似问题