Skip to main content

How to cache JSON data in Redis with Go


Profile picture for Ajeet Raina
Author:
Ajeet Raina, Former Developer Growth Manager at Redis

Go-ReJSON is a Go client for Redis JSON feature. It is a Golang client that support multiple Redis clients such as the print-like Redis-api client redigo and the type-safe Redis client go-redis.

Follow the below steps to get started with Redis JSON using Go client.

Step 1. Initialize the Go feature

 go mod init github.com/my/repo

Step 2. Install Go-redis

 go get github.com/go-redis/redis/v8

Step 3. Install Go client for Redis JSON

 go get github.com/nitishm/go-rejson/v4

Step 4. Clone the repository

 git clone https://github.com/nitishm/go-rejson
cd go-rejson/example

Step 5. Build the Go package

Command:
 go build json_set/json_set.go
Result:
 go: downloading github.com/go-redis/redis/v8 v8.4.4
go: downloading github.com/gomodule/redigo v1.8.3
go: downloading go.opentelemetry.io/otel v0.15.0
go build: build output "json_set" already exists and is a directory

Step 6. Run the Go program

Command:
 go run json_set/json_set.go
Result:
 Executing Example_JSONSET for Redigo Client
Success: OK
Student read from redis : main.Student{Name:main.Name{First:"Mark", Middle:"S", Last:"Pronto"}, Rank:1}

Executing Example_JSONSET for Redigo Client
Success: OK
Student read from redis : main.Student{Name:main.Name{First:"Mark", Middle:"S", Last:"Pronto"}, Rank:1}
Command:
 pwd
go-rejson/examples
Command:
 go run json_array/json_array.go
Result:
 Executing Example_JSONSET for Redigo Client
arr: OK
arr before pop: [one two three four five]
Length: 5
Deleted element: five
arr after pop: [one two three four]
Length: 4
Index of "one": 0
Out of range: -1
"ten" not found: -1
no. of elements left: 2
arr after trimming to [1,2]: [two three]
no. of elements: 3
arr after inserting "one": [one two three]

Executing Example_JSONSET for Redigo Client
arr: OK
arr before pop: [one two three four five]
Length: 5
Deleted element: five
arr after pop: [one two three four]
Length: 4
Index of "one": 0
Out of range: -1
"ten" not found: -1
no. of elements left: 2
arr after trimming to [1,2]: [two three]
no. of elements: 3
arr after inserting "one": [one two three]

References