Golang中rejson的使用 - Go语言中文社区

Golang中rejson的使用


redis原生是不支持直接存储json格式的数据的,而rejson则是专门的可以支持json格式一个插件。通过rejson,我们可以快速的操作json数据的读、写、更新、删除、修改等操作。

需要注意的是:

rejson是对redis功能的扩展,使用rejson命令操作的数据,无法用redis命令操作;同样,使用redis命令操作的数据,无法使用rejson操作。因为两者的操作数据格式完全不一样,rejson二进制数据存储的。

在rejson的官网中实现rejson相关功能的开源库如下:

在这里插入图片描述

其中golang的开源库有两个,go-rejson和jonson,他们分别使用了redis的开源client库redigo和go-redis。根据rejson的官网使用指南,我们可以知道,rejson如同是redis命令的扩展,如此我们可知go-rejson和jonson不过是在redis上封装了使用的扩展命令而已。你如果对redis比较熟悉的话,你也可以封装个属于自己的rejson库。这里,我们介绍下使用相对较多的go-rejson。

go-rejson的主页面,我们可以看到有部分功能并没有实现,作者在Issues中提到太忙,没时间维护,需要人帮忙来维护。哈哈,上面我们提到了rejson只是在redigo上的简单命令调用实现,因此我们可以在作者的基础上,仿照基本的格式进行实现。这是我们实现的go-rejson分支,已经实现了其余的功能哦。

如下是我们的实现的部分代码(注释来自于rejson官方命令哦)

//JSON.ARRINDEX return the position of the scalar value in the array, or -1 if unfound.
//JSON.ARRINDEX <key> <path> <json-scalar> [start [stop]]
//The optional inclusive start (default 0) and exclusive stop (default 0, meaning that the last element is included) specify a slice of the array to search.
func JSONArrIndex(conn redis.Conn, key string, path string, scalar interface{}, start int, stop int) (res interface{}, err error) {
	name, args, _ := CommandBuilder("JSON.ARRINDEX", key, path, scalar, start, stop)
	return conn.Do(name,args...)
}

//JSON.ARRPOP Remove and return element from the index in the array.
//JSON.ARRPOP <key> [path [index]]
//index is the position in the array to start popping from (defaults to -1, meaning the last element).
func JSONArrPop(conn redis.Conn, key string, path string, index int) (res interface{}, err error) {
	name, args, _ := CommandBuilder("JSON.ARRPOP", key, path,index)
	return conn.Do(name,args...)
}

//JSON.ARRTRIM Trim an array so that it contains only the specified inclusive range of elements.
//JSON.ARRTRIM <key> <path> <start> <stop>
func JSONArrTrim(conn redis.Conn, key string, path string, start int, stop int) (res interface{}, err error) {
	name, args, _ := CommandBuilder("JSON.ARRTRIM", key, path, start, stop)
	return conn.Do(name,args...)
}

//JSON.OBJKEYS Return the keys in the object that's referenced by path.
//JSON.OBJKEYS <key> [path]
func JSONObjKeys(conn redis.Conn, key string, path string) (res interface{}, err error) {
	name, args, _ := CommandBuilder("JSON.OBJKEYS", key, path)
	return conn.Do(name,args...)
}

//JSON.OBJLEN Report the number of keys in the JSON Object at path in key.
//JSON.OBJLEN  <key> [path]
func JSONObjLen(conn redis.Conn, key string, path string) (res interface{}, err error) {
	name, args, _ := CommandBuilder("JSON.OBJLEN", key, path)
	return conn.Do(name,args...)
}

其他的方法见go-rejson分支,欢迎star和fork哦。

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/xz_studying/article/details/84638256
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-08-25 15:28:24
  • 阅读 ( 2430 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢