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;
        }
    }

 


版权声明:本文为Lfanmujin原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。