nioshield / go-elect

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

go-elect

go-elect is a library for making the election process easier. It provides a simple interface for managing your distributed exclusive job execution, and it supports multiple backends for storing the election state:

And more to come...

How to use

Redis

package main

import (
    "github.com/redis/go-redis/v9"
    "github.com/git-hulk/go-elect/elector/engine/store"
    "github.com/git-hulk/go-elect/elector"
)

type CountRunner struct {
    count atomic.Int32
}

func (r *CountRunner) Run(_ context.Context) error {
    r.count.Inc()
    time.Sleep(100 * time.Millisecond)
    return nil
}

func main() {
    ctx := context.Background()
    redisClient := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
    redisStore := store.NewRedisStore(redisClient)
	
    elector, err := elector.New(redisStore, "test-elector1-key", 3 * time.Second,  &CountRunner{})
    if err := elector.Run(ctx);  err != nil {
        // handle error
    }
    elector.Wait()
    // use elector.Release() to release the election
}

License

About

License:Apache License 2.0


Languages

Language:Go 97.6%Language:Makefile 1.4%Language:Shell 1.0%