字符串String实战之商品对象信息缓存管理之修改与删除

stringService.java

    //修改
    @Transactional(rollbackFor = Exception.class)
    public Integer update(Item item) throws  Exception{
       int res = itemMapper.updateByPrimaryKeySelective(item);
        //数据库修改成功,也同时往cache写一份。保证双写一致性
        if(res > 0){
            //利用ObjectMapper将结果转换成字符串格式
            redisTemplate.opsForValue().set(Constant.RedisStringPrefix+item.getId(), objectMapper.writeValueAsString(item));
        }
        return  item.getId();
    }

    //删除
    public Integer delete(final Integer id) throws Exception{
        int res = itemMapper.deleteByPrimaryKey(id);
         //数据库中删除了以后,缓存中也需要删除
        if(res > 0){
            redisTemplate.delete(Constant.RedisStringPrefix+id);
        }
        return 1;
    }

stringController.java

   //修改
    @RequestMapping(value = "update", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResponse update(@RequestBody @Validated Item item, BindingResult result){
        String checkRes = ValidatorUtil.checkResult(result);
        if(StringUtils.isNotBlank(checkRes)){
            return new BaseResponse(StatusCode.InvalidParams.getCode(), checkRes);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);

        try{
            response.setData(stringService.update(item));
        }catch (Exception e){
            log.error("商品对象信息的管理-缓存-修改-异常信息: ", e);
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }

    //删除
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public BaseResponse update(@RequestParam Integer id){
        if(id <= 0){
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);

        try{
            response.setData(stringService.delete(id));
        }catch (Exception e){
            log.error("商品对象信息的管理-缓存-删除-异常信息: ", e);
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }

猜你喜欢

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