play.cache.Cache类提供了一系列访问缓存的API,包含了完整的设置、替换和获取数据的方法:
public static void showProduct(String id) {
Product product = Cache.get(id, Product.class);
if(product == null) {
product = Product.findById(id);
Cache.set("product_"+id, product, "30mn");
}
render(product);
}
public static void addProduct(String name, int price) {
Product product = new Product(name, price);
product.save();
showProduct(id);
}
public static void editProduct(String id, String name, int price) {
Product product = Product.findById(id);
product.name = name;
product.price = price;
Cache.set("product_"+id, product, "30mn");
showProduct(id);
}
public static void deleteProduct(String id) {
Product product = Product.findById(id);
product.delete();
Cache.delete("product_"+id);
allProducts();
}
操作缓存的API中有很多方法是以safe作为前缀的,如safeDelete,safeSet等。带safe前缀的方法是阻塞的,而标准方法是非阻塞的,delete方法会立即返回结果,并没有等待缓存对象是否被真正地物理删除。因此,如果程序执行期间发生了错误(例如IO错误),缓存对象可能仍然存在,并没有被删除。如果操作需要确保缓存对象被删除,可以使用safeDelete方法:
Cache.safeDelete("myProduct_"+id);
配置Memcachedmemcached=enabled
memcached.host=127.0.0.1:11211
缓存服务器可以设置多个,存缓存的时候也是可以制定缓存的。