取某个商品的基本信息并添加缓存逻辑 service
package com.taotao.rest.service.impl; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.taotao.common.pojo.TaotaoResult; import com.taotao.common.utils.JsonUtils; import com.taotao.mapper.TbItemMapper; import com.taotao.pojo.TbItem; import com.taotao.rest.dao.JedisClient; import com.taotao.rest.service.ItemService; @Service public class ItemServiceImpl implements ItemService { @Autowired private TbItemMapper itemMapper; @Autowired private JedisClient jedisClient; @Value("${REDIS_ITEM_KEY}") private String REDIS_ITEM_KEY; @Value("${REDIS_ITEM_EXPIRE}") private int REDIS_ITEM_EXPIRE; //根据id查询商品信息 @Override public TaotaoResult getItemBaseInfo(Long itemId) { TbItem item = null; //添加缓存逻辑 //从缓存中取商品信息,商品id对应的信息 String key = REDIS_ITEM_KEY+":"+itemId+":base"; try { //从缓存中取商品信息 String json = jedisClient.get(key); //判断是否有值 if (StringUtils.isNotEmpty(json)) { //如果有值,转成java对象 item = JsonUtils.jsonToPojo(json, TbItem.class); //直接返回 return TaotaoResult.ok(item); } } catch (Exception e1) { e1.printStackTrace(); } //从数据库中查询 item = itemMapper.selectByPrimaryKey(itemId); //把商品信息写入缓存(不能影响正常业务逻辑,所以需要给添加缓存的代码加入try catch) try { jedisClient.set(key, JsonUtils.objectToJson(item)); jedisClient.expire(key, REDIS_ITEM_EXPIRE); } catch (Exception e) { e.printStackTrace(); } return TaotaoResult.ok(item); } }