字符串String实战之商品对象缓存管理之新增与获取详情

1. 新创建item表

CREATE TABLE `item` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(255) DEFAULT NULL COMMENT '商品编号',
  `name` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '商品名称',
  `create_time` datetime DEFAULT NULL,
  `content` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_code` (`code`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=10014 DEFAULT CHARSET=utf8 COMMENT='商品信息表';

2. 逆向工程生成mapper,entity和mapper.xml文件

3. 针对redis中的key创建一个Constant类

public class Constant {
    public static final String RedisStringPrefix = "SpringBootRedis:String:V1";
}

4. StringController.java

@RestController
@RequestMapping("string/item")
public class StringController {

    private static final Logger log = LoggerFactory.getLogger(StringController.class);

    @Autowired
    private StringService stringService;

    //新增(表示数据提交的格式为json)
    @RequestMapping(value = "add", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResponse add(@RequestBody @Validated Item item, BindingResult result){
        if(result.hasErrors()){
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try{
            response.setData(stringService.add(item));
        }catch (Exception e){
            log.error("商品对象信息的管理-缓存新增-异常信息", e);
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }

    //详情
    @RequestMapping(value = "info", method = RequestMethod.GET)
    public BaseResponse add(@RequestParam Integer id){
        if(id <= 0){
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try{
            response.setData(stringService.get(id));
        }catch (Exception e){
            log.error("商品对象信息的管理-缓存-详情-异常信息", e);
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }

}

5.StringService.java

@Service
public class StringService {
    private static final Logger log = LoggerFactory.getLogger(StringService.class);

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Transactional(rollbackFor = Exception.class)
    public Integer add(Item item) throws  Exception{
        item.setCreateTime(new Date());
        item.setId(null);
        int res = itemMapper.insertSelective(item);

        //数据库写入成功,也同时往cache写一份。保证双写一致性
        if(res > 0){
            //利用ObjectMapper将结果转换成字符串格式
            redisTemplate.opsForValue().set(Constant.RedisStringPrefix+item.getId(), objectMapper.writeValueAsString(item));
        }
        return  item.getId();
    }
    //有缓存就直接在缓存中掺查找,没有缓存的话就需要查询数据库
    public Item get(final Integer id) throws Exception{
        final  String key = Constant.RedisStringPrefix + id;
        Item item = null;
        if(redisTemplate.hasKey(key)){
            Object obj = redisTemplate.opsForValue().get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                item = objectMapper.readValue(obj.toString(), Item.class);
            }
        }else{
            item = itemMapper.selectByPrimaryKey(id);
            //如果从数据库中查找到了结果的话,重新放置回缓存
            if(item != null){
                redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(item));
            }
            else{
                //防止缓存穿透
                redisTemplate.opsForValue().set(key, "");
            }
        }
        return item;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_37841366/article/details/109136155