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哦。