# 1.简介

RedisJSON 是一个 Redis 模块,它实现了 ECMA-404 JSON 数据交换标准作为原生数据类型。它允许从 Redis 键(文档)存储、更新和获取 JSON 值。

特点

  • 完全支持JSON标准
  • 使用类似JSONPath的语法,用于在文档中选择元素
  • 文档以二进制数据的形式存储在树结构中,允许快速访问子元素
  • 所有JSON值类型都是原子操作

项目地址:https://github.com/RedisJSON/RedisJSON (opens new window)

官网:https://oss.redis.com/redisjson (opens new window)

客户端:https://oss.redis.com/redisjson/#client-libraries (opens new window)

# 2.安装

docker run -p 6379:6379 --name redis-redisjson redislabs/rejson:latest
1

或者下载官方模块进行加载

方式1:
redis-server --loadmodule /usr/lib/redis/module/rejson.so

方式2:
在redis.conf中,添加一下内容:
loadmodule /usr/lib/redis/module/rejson.so
1
2
3
4
5
6

# 3. 简单使用

简单字符串操作

127.0.0.1:6379> JSON.SET foo . '"bar"'
OK
127.0.0.1:6379> JSON.GET foo
"\"bar\""
127.0.0.1:6379> JSON.TYPE foo
"string"
127.0.0.1:6379>
127.0.0.1:6379> JSON.STRLEN foo
(integer) 3
127.0.0.1:6379> JSON.STRLEN foo .
(integer) 3
127.0.0.1:6379> JSON.STRAPPEND foo . '"baz"'
(integer) 6
127.0.0.1:6379> JSON.GET foo
"\"barbaz\""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

数字操作

127.0.0.1:6379> JSON.SET num . 0
OK
127.0.0.1:6379> JSON.NUMINCRBY num . 1
"1"
127.0.0.1:6379> JSON.NUMINCRBY num . 1
"2"
127.0.0.1:6379> JSON.NUMINCRBY num . 1.5
"3.5"
127.0.0.1:6379> JSON.NUMINCRBY num . -0.75
"2.75"
127.0.0.1:6379> JSON.NUMMULTBY num . 24
"66"
1
2
3
4
5
6
7
8
9
10
11
12

数组操作

127.0.0.1:6379> JSON.SET arr . []
OK
127.0.0.1:6379> json.get arr
"[]"
127.0.0.1:6379> JSON.ARRAPPEND arr . 0
(integer) 1
127.0.0.1:6379> JSON.GET arr
"[0]"
127.0.0.1:6379> JSON.ARRINSERT arr . 0 -2 -1
(integer) 3
127.0.0.1:6379> json.get add
(nil)
127.0.0.1:6379> json.get arr
"[-2,-1,0]"
127.0.0.1:6379> JSON.ARRTRIM arr . 1 1
(integer) 1
127.0.0.1:6379> JSON.GET arr
"[-1]"
127.0.0.1:6379> JSON.ARRPOP arr
"-1"
127.0.0.1:6379> JSON.ARRPOP arr
(nil)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

object操作

127.0.0.1:6379> JSON.SET obj . '{"name":"Leonard Cohen","lastSeen":1478476800,"loggedOut": true}'
OK
127.0.0.1:6379> JSON.OBJLEN obj .
(integer) 3
127.0.0.1:6379> JSON.OBJKEYS obj .
1) "name"
2) "lastSeen"
3) "loggedOut"
1
2
3
4
5
6
7
8

# 4.参考资料

官方命令 (opens new window)