Redis 存储对象 《一》 使用JSON字符串

redis的存取方式是通过Key—Value的方式。

那么要将对象存储进去,需要将对象转化为JSON字符串

首先pom.xml 添加依赖

<!-- Jeson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

然后创建一个类 DDoc 

package com.muzi.museum.bean;


public class DDoc  {
    private Integer id;

    private String title;

    private String type;

    private String description;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type == null ? null : type.trim();
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description == null ? null : description.trim();
    }
}

 在serviceImpl的方法实现中

 @Override

    public DDoc selectByPrimaryKey(int id) {
        //缓存中获取信息
        String key = "ddoc:" + id;
        //缓存存在
        boolean haskey = stringRedisTemplate.hasKey(key);
        if(haskey){
            String json = stringRedisTemplate.opsForValue().get(key);
            DDoc dDoc = JSONObject.parseObject(json,DDoc.class);
            LOGGER.info("从缓存中读取到DDoc"+"id:"+dDoc.getId());
            return dDoc;
        }
        else {
            DDoc dDoc;
            //从DB中获取用户的值
            dDoc = dDocMapper.selectByPrimaryKey(id);
            //写入缓存
            if (dDoc != null) {
                stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(dDoc));
                LOGGER.info("DDoc写入缓存" + "id:" + dDoc.getId());
            }
            return dDoc;
        }
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值