添加缓存实例

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

}

posted on 2017-06-07 23:23  尴尬而不失礼貌的微笑  阅读(338)  评论(0编辑  收藏  举报