Created
August 26, 2022 14:27
-
-
Save lambrospetrou/53962e22939341ab04926b7fb45aa3b9 to your computer and use it in GitHub Desktop.
Use Upstash Redis - rest and native clients from Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"context" | |
"log" | |
"net/http" | |
"sync" | |
"time" | |
"github.com/go-redis/redis/v8" | |
) | |
var ctx = context.Background() | |
func redisRest(urlPath string) string { | |
req, _ := http.NewRequest(http.MethodGet, "https://eu1-actual-dragon-11111.upstash.io"+urlPath, nil) | |
req.Header.Add("Authorization", "Bearer <REPLACE_THIS_WITH_YOUR_REST_TOKEN>") | |
resp, err := http.DefaultClient.Do(req) | |
if err != nil { | |
panic(err) | |
} | |
defer resp.Body.Close() | |
s, _ := bufio.NewReader(resp.Body).ReadString('|') | |
return s | |
} | |
func timeit(name string, f func()) { | |
start := time.Now() | |
f() | |
duration := time.Since(start) | |
log.Println(name+" elapsed time: ", duration) | |
} | |
func main() { | |
opt, _ := redis.ParseURL("rediss://:<REPLACE_THIS_WITH_YOUR_DB_PASSWORD>@eu1-actual-dragon-11111.upstash.io:38214") | |
client := redis.NewClient(opt) | |
var wg sync.WaitGroup | |
for j := 0; j < 10; j++ { | |
wg.Add(1) | |
go timeit("go-redis", func() { | |
for i := 0; i < 10; i++ { | |
client.Set(ctx, "foo", "bar", 0) | |
client.Get(ctx, "foo").Val() | |
client.HSet(ctx, "foohash", "barkey", "hashval", "bar2key", "bar2val") | |
client.HGet(ctx, "foohash", "barkey") | |
} | |
wg.Done() | |
}) | |
} | |
for j := 0; j < 10; j++ { | |
wg.Add(1) | |
go timeit("rest redis", func() { | |
for i := 0; i < 10; i++ { | |
redisRest("/set/foo-rest/bar") | |
redisRest("/get/foo-rest") | |
redisRest("/hset/foohash-rest/barkey/hashval/bar2key/bar2val") | |
redisRest("/hget/foohash-rest/barkey") | |
} | |
wg.Done() | |
}) | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment