@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);
}
}