Redis实战(2)-数据结构之字符串String实战之存储对象

摘要:在Redis众多数据结构当中,字符串String可以说是其中比较常见、应用比较频繁的一种了,本文我们将介绍数据类型~字符串String 在命令行的简单使用及其在实际业务场景中的应用与代码实战,其中应用场景为“存储前端门户网站的商品详情信息”,从而减少数据库DB的访问频率,提高接口的响应速率!

内容:缓存中间件Redis拥有多种丰富的数据结构,字符串String就是其中比较常见而且应用相当广泛的一种,下面我们将基于前文整合搭建的SpringBoot2.0+Redis的项目为奠基,从两个方面进行介绍,即简单的命令行实际的应用场景+代码实战

(一)Redis命令行界面实操“数据类型String”

(1)由于Debug本地机子是windows系统,故而为了可以在本地windows操作系统的机子使用Redis命令行,我们需要前往github下载一个windows版的redis绿色安装工具包(如果是mac或者linux,则直接跳过此步骤),为了方便大家下载,我就直接提供地址给大家下载了(链接:百度网盘 请输入提取码 提取码:isj0)

下载完成之后,解压到没有中文名称的磁盘目录下,如下图所示:

其中,最主要的文件当属redis-server.exe、redis-cli.exe以及另外两个用于数据持久化的rdb和aof文件,双击redis-server.exe,成功出现如下的界面即代表redis已经成功在你本地运行起来了:

(2)下面,我们写两个简单的命令(即如何往Redis存入一个Key,以及如何从Redis中获取该Key对应的值),简单的感受一下字符串String在Redis命令行界面下的操作,如下图所示:

是不是感觉很简单???哈哈,本来就是如此!除此之外,还可以在RedisDesktopManager工具查看该Key的具体值!下面我进入重头戏,即如何将Redis的这些特性应用到实际的项目、实际的业务场景中去呢!

(二)String典型应用场景代码实战

(1)业务场景介绍:下面我们以“访问前端门户网站商品信息”为业务场景,在后端管理平台添加“热门商品信息”时也顺便将其塞入缓存Redis中,之后前端门户网站在获取该商品详情时直接走缓存Redis查询,而不走数据库DB查询,在某种情况下(比如双11、双12的热销商品),可以缓解数据库的访问压力,降低DB的负载!

(2)我们首先开发一个Controller,用于添加热门商品信息、并将其塞入缓存Redis中,除此之外,还开发了前端门户网站访问该热门商品详情信息的请求方法,其完整的源码如下所示:

/**
 * 字符串String实战-商品详情存储
 * @Author:debug (SteadyJack)
 * @Link: weixin-> debug0868 qq-> 1948831260
 * @Date: 2019/10/29 20:58
 **/
@RestController
@RequestMapping("string")
public class StringController {

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

    @Autowired
    private StringService stringService;

    //添加热门商品
    @RequestMapping(value = "put",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResponse put(@RequestBody @Validated Item item, BindingResult result){
        if (result.hasErrors()){
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            log.info("--商品信息:{}",item);

            stringService.addItem(item);
        }catch (Exception e){
            log.error("--字符串String实战-商品详情存储-添加-发生异常:",e.fillInStackTrace());
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    //获取热门商品详情
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public BaseResponse get(@RequestParam Integer id){
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            response.setData(stringService.getItem(id));

        }catch (Exception e){
            log.error("--字符串String实战-商品详情存储-添加-发生异常:",e.fillInStackTrace());
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }
}

(3)其中,stringService 顾名思义,即为实现业务逻辑的真正实现类!其完整源代码如下所示:  

/**
 * @Author:debug (SteadyJack)
 * @Link: weixin-> debug0868 qq-> 1948831260
 * @Date: 2019/10/29 21:05
 **/
@Service
public class StringService {

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

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private StringRedisService redisService;

    @Autowired
    private ObjectMapper objectMapper;


    //添加商品
    @Transactional(rollbackFor = Exception.class)
    public Integer addItem(Item item) throws Exception{
        item.setCreateTime(new Date());
        item.setId(null);
        itemMapper.insertSelective(item);
        Integer id=item.getId();

        //保证缓存-数据库双写的一致性
        if (id>0){
            redisService.put(id.toString(),objectMapper.writeValueAsString(item));
        }
        return id;
    }

    //获取商品
    public Item getItem(Integer id) throws Exception{
        Item item=null;
        if (id!=null){
            if (redisService.exist(id.toString())){
                String result=redisService.get(id.toString()).toString();
                log.info("---string数据类型,从缓存中取出来的value:{}",result);
                if (StrUtil.isNotBlank(result)){
                    item=objectMapper.readValue(result,Item.class);
                }
            }else{
                log.info("---string数据类型,从数据库查询:id={}",id);

                item=itemMapper.selectByPrimaryKey(id);
                if (item!=null){
                    redisService.put(id.toString(),objectMapper.writeValueAsString(item));
                }
            }
        }
        return item;
    }
}

更多请见:http://www.mark-to-win.com/tutorial/51074.html 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值