实现JVM进程缓存
需求
利用Caffeine實(shí)現(xiàn)下列需求:
-
給根據(jù)id查詢商品的業(yè)務(wù)添加緩存,緩存未命中時(shí)查詢數(shù)據(jù)庫(kù)
-
給根據(jù)id查詢商品庫(kù)存的業(yè)務(wù)添加緩存,緩存未命中時(shí)查詢數(shù)據(jù)庫(kù)
-
緩存初始大小為100
-
緩存上限為10000
實(shí)現(xiàn)
首先,我們需要定義兩個(gè)Caffeine的緩存對(duì)象,分別保存商品、庫(kù)存的緩存數(shù)據(jù)。
在item-service的com.leon.item.config包下定義CaffeineConfig類:
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;@Configuration public class CaffeineConfig {@Beanpublic Cache<Long, Item> itemCache(){return Caffeine.newBuilder().initialCapacity(100).maximumSize(10_000).build();}@Beanpublic Cache<Long, ItemStock> stockCache(){return Caffeine.newBuilder().initialCapacity(100).maximumSize(10_000).build();} }然后,修改item-service中的com.leon.item.web包下的ItemController類,添加緩存邏輯:
@RestController @RequestMapping("item") public class ItemController {@Autowiredprivate IItemService itemService;@Autowiredprivate IItemStockService stockService;@Autowiredprivate Cache<Long, Item> itemCache;@Autowiredprivate Cache<Long, ItemStock> stockCache;// ...其它略@GetMapping("/{id}")public Item findById(@PathVariable("id") Long id) {return itemCache.get(id, key -> itemService.query().ne("status", 3).eq("id", key).one());}@GetMapping("/stock/{id}")public ItemStock findStockById(@PathVariable("id") Long id) {return stockCache.get(id, key -> stockService.getById(key));} }總結(jié)
- 上一篇: 初识Caffeine
- 下一篇: 初识Lua