看上图
赋代码:
<dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> </dependency>
package com.heima.item.config; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.heima.item.pojo.Item; import com.heima.item.pojo.ItemStock; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CaffeineConfig { @Bean public Cache<Long, Item> itemCache(){ return Caffeine.newBuilder() .initialCapacity(100) .maximumSize(10_000) .build(); } @Bean public Cache<Long, ItemStock> stockCache(){ return Caffeine.newBuilder() .initialCapacity(100) .maximumSize(10_000) .build(); } }
@Autowired private Cache<Long,Item> itemCache; @Autowired private 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)); }
package com.heima.item.pojo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; @Data @TableName("tb_item") public class Item { @TableId(type = IdType.AUTO) private Long id;//商品id private String name;//商品名称 private String title;//商品标题 private Long price;//价格(分) private String image;//商品图片 private String category;//分类名称 private String brand;//品牌名称 private String spec;//规格 private Integer status;//商品状态 1-正常,2-下架 private Date createTime;//创建时间 private Date updateTime;//更新时间 @TableField(exist = false) private Integer stock; @TableField(exist = false) private Integer sold; }
package com.heima.item.pojo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data @TableName("tb_item_stock") public class ItemStock { @TableId(type = IdType.INPUT, value = "item_id") private Long id; //商品id private Integer stock; //商品库存 private Integer sold; //商品销量 }
Item,ItemStock 是什么无所谓,就是个pojo ,万物皆可存。