Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cghiban/6e58e673eb596177e94c13d1b0e32c20 to your computer and use it in GitHub Desktop.
Save cghiban/6e58e673eb596177e94c13d1b0e32c20 to your computer and use it in GitHub Desktop.
Super simple Redis circular-buffer written on GO

Super simple Redis circular-buffer on GO

Here you can find super simple redis based circular-buffer implementation written on golang:

package main

import (
	"fmt"
	"log"
	"strconv"
	"time"

	radix "github.com/mediocregopher/radix/v3"
)

const (
	RedisAddr     = "localhost:6379"
	RedisPoolSize = 3
)

func main() {
	circularBuffer()
}

func getPool() *radix.Pool {
	f := radix.PoolConnFunc(func(network, addr string) (radix.Conn, error) {
		client, err := radix.Dial(network, addr)
		if err != nil {
			return nil, err
		}

		if err = client.Do(radix.Cmd(nil, "SELECT", "1")); err != nil {
			if e := client.Close(); e != nil {
				return nil, e
			}
			return nil, err
		}

		return client, nil
	})
	i := radix.PoolPingInterval(1 * time.Second)
	p, err := radix.NewPool("tcp", RedisAddr, RedisPoolSize, f, i)
	if err != nil {
		panic(fmt.Errorf("failed to create redis pool , error: %w", err))
	}

	return p
}

func circularBuffer() {
	s := `
		redis.call('LPUSH', KEYS[1], ARGV[1])
		redis.call('LTRIM', KEYS[1], 0, 5)
	`
	res := ""
	v := strconv.FormatInt(time.Now().Unix(), 10)
	script := radix.NewEvalScript(1, s).Cmd(&res, "cb", v)

	p := getPool()
	err := p.Do(script)
	if err != nil {
		panic(fmt.Errorf("failed to run redis script , error: %w", err))
	}

	log.Printf("got result: %#v", res)
}

PS

You can find more stuff like this in my demo repo.
Source code, examples, explanation info, etc. just go and check it out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment