DEV Community

Tarek Ali
Tarek Ali

Posted on • Updated on

How I solved SQL to Redis caching with Go

Problem

I wanted a library to abstract copying data from MySQL + Postgres to Redis for the purpose of caching, none were present at the time.

Solution

Introducing, redisql, a Go module and command-line tool that allows you to convert SQL tables to a desired Redis datatype with one method call.

Example

Let's start with a celebrity table:

mysql> DESCRIBE celebrity; 
+-------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------+------+-----+---------+-------+
| name  | text | YES  |     | NULL    |       |
| age   | int  | YES  |     | NULL    |       |
+-------+------+------+-----+---------+-------+
2 rows in set (0.01 sec)
Enter fullscreen mode Exit fullscreen mode

Now we incorporate redisql:

package main

import (
    "github.com/DGKSK8LIFE/redisql"
)

func main() {
    config := redisql.Config{
        SQLType:     "mysql",
        SQLUser:     "user",
        SQLPassword: "password",
        SQLDatabase: "celebrities",
        SQLHost:     "localhost",
        SQLPort:     "3306",
        SQLTable:    "celebrity",
        RedisAddr:   "localhost:6379",
        RedisPass:   "password",
    }
    err := config.CopyToString()
    if err != nil {
        panic(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

In redis-cli:

127.0.0.1:6379> get celebrity:0:name
"Jaden Smith"
Enter fullscreen mode Exit fullscreen mode

If we wanted to copy to other datatypes:

// copy to redis list
config.CopyToList()

// copy to redis hash
config.CopyToHash()
Enter fullscreen mode Exit fullscreen mode

Discussion (0)