我是靠谱客的博主 野性大侠,这篇文章主要介绍Redis 存储对象 《一》 使用JSON字符串,现在分享给大家,希望可以做个参考。

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

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

首先pom.xml 添加依赖

复制代码
1
2
3
4
5
6
<!-- Jeson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>

然后创建一个类 DDoc 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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的方法实现中

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@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; } }

 

最后

以上就是野性大侠最近收集整理的关于Redis 存储对象 《一》 使用JSON字符串的全部内容,更多相关Redis内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(96)

评论列表共有 0 条评论

立即
投稿
返回
顶部