添加緩存實例
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
private TbItemMapper itemMapper;
@Value("${REDIS_ITEM_KEY}")
private String REDIS_ITEM_KEY;
@Value("${REDIS_ITEM_EXPIRE}")
private Integer REDIS_ITEM_EXPIRE;
@Autowired
private JedisClient jedisClient;
@Override
public TaotaoResult getItemBaseInfo(long itemId) {
try {
//添加緩存邏輯
//從緩存中取商品信息,商品id對應的信息
String json = jedisClient.get(REDIS_ITEM_KEY + ":" + itemId + ":base");
//判斷是否有值
if (!StringUtils.isBlank(json)) {
//把json轉換成java對象
TbItem item = JsonUtils.jsonToPojo(json, TbItem.class);
return TaotaoResult.ok(item);
}
} catch (Exception e) {
e.printStackTrace();
}
//根據商品id查詢商品信息
TbItem item = itemMapper.selectByPrimaryKey(itemId);
//使用TaotaoResult包裝一下
try {
//把商品信息寫入緩存
jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":base", JsonUtils.objectToJson(item));
//設置key的有效期
jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId + ":base", REDIS_ITEM_EXPIRE);
} catch (Exception e) {
e.printStackTrace();
}
return TaotaoResult.ok(item);
}
}
添加緩存實例