Advertisement
exapsy

local_and_redis_bench

May 22nd, 2024
678
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.33 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "context"
  5.     "fmt"
  6.     "time"
  7.  
  8.     "github.com/redis/go-redis/v9"
  9. )
  10.  
  11. var S = ""
  12.  
  13. const REDIS_HOST = "myredisisntance.com"
  14.  
  15. var localcache = make(map[string]string)
  16.  
  17. func main() {
  18.   ctx := context.Background()
  19.  
  20.   rdb := redis.NewClient(&redis.Options{
  21.     Addr: REDIS_HOST + ":6379",
  22.     Password: "",
  23.     DB: 0,
  24.   })
  25.  
  26.   err := rdb.Ping(ctx).Err()
  27.   if err != nil {
  28.     panic(err)
  29.   }
  30.  
  31.   err = rdb.Set(ctx, "key", "value", 0).Err()
  32.   if err != nil {
  33.     panic(err)
  34.   }
  35.  
  36.   totalRedisGetTime := time.Duration(0)
  37.   totalLocalGetTime := time.Duration(0)
  38.  
  39.   for i := 0; i < 1000; i++ {
  40.  
  41.     if i == 1 || i %100 == 0 {
  42.       fmt.Printf("Progress: %v/1000\n", i)  
  43.     }
  44.  
  45.     totalRedisGetTime += getFromRedis(rdb, "key")
  46.     totalLocalGetTime += getFromLocalCache("key")
  47.   }
  48.  
  49.   fmt.Printf("Total time to get from Redis: %v\n", totalRedisGetTime)
  50.   fmt.Printf("Total time to get from Local Cache: %v\n", totalLocalGetTime)
  51. }
  52.  
  53. func getFromRedis(rdb *redis.Client, key string) time.Duration {
  54.   start := time.Now()
  55.   var err error
  56.   ctx := context.Background()
  57.   S, err = rdb.Get(ctx, key).Result()
  58.   if err != nil {
  59.     panic(err)
  60.   }
  61.   return time.Since(start)
  62. }
  63.  
  64. func getFromLocalCache(key string) time.Duration {
  65.   start := time.Now()
  66.   S = localcache[key]
  67.   return time.Since(start)
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement