Redis player count for clustering
This commit is contained in:
@@ -1,11 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis/v9"
|
||||
"github.com/hashicorp/consul/api"
|
||||
"go.minekube.com/brigodier"
|
||||
. "go.minekube.com/common/minecraft/component"
|
||||
@@ -53,7 +57,7 @@ func (p *FenceProxy) init() error {
|
||||
func (p *FenceProxy) registerServers() {
|
||||
// Get a new client
|
||||
config := api.DefaultConfig()
|
||||
config.Address = "consul1.pawott.de:8500"
|
||||
config.Address = getEnv("CONSUL_ADDR", "127.0.0.1:8500")
|
||||
client, err := api.NewClient(config)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -164,11 +168,28 @@ func (p *FenceProxy) registerCommands() {
|
||||
))
|
||||
}
|
||||
|
||||
var ctx = context.Background()
|
||||
var localPlayers int64 = 0
|
||||
|
||||
// Register event subscribers
|
||||
func (p *FenceProxy) registerSubscribers() error {
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: getEnv("REDIS_ADDR", "localhost:6379"),
|
||||
Password: "", // no password set
|
||||
DB: 0, // use default DB
|
||||
})
|
||||
|
||||
p.Event().Subscribe(&proxy.PingEvent{}, 0, func(ev event.Event) {
|
||||
e := ev.(*proxy.PingEvent)
|
||||
p := e.Ping()
|
||||
val, err := rdb.Get(ctx, "players").Result()
|
||||
if err == redis.Nil {
|
||||
// does not exist yet
|
||||
rdb.Set(ctx, "players", 0, 0)
|
||||
} else if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
p.Players.Online, _ = strconv.Atoi(val)
|
||||
p.Players.Max = p.Players.Online + 1
|
||||
})
|
||||
p.Event().Subscribe(&proxy.LoginEvent{}, 0, func(ev event.Event) {
|
||||
@@ -178,16 +199,25 @@ func (p *FenceProxy) registerSubscribers() error {
|
||||
p.Event().Subscribe(&proxy.PlayerChooseInitialServerEvent{}, 0, func(ev event.Event) {
|
||||
e := ev.(*proxy.PlayerChooseInitialServerEvent)
|
||||
e.SetInitialServer(p.Servers()[0])
|
||||
localPlayers += 1
|
||||
rdb.Incr(ctx, "players")
|
||||
})
|
||||
|
||||
p.Event().Subscribe(&proxy.DisconnectEvent{}, 0, func(ev event.Event) {
|
||||
localPlayers -= 1
|
||||
rdb.Decr(ctx, "players")
|
||||
})
|
||||
|
||||
p.Event().Subscribe(&proxy.ShutdownEvent{}, 0, func(ev event.Event) {
|
||||
rdb.DecrBy(ctx, "players", localPlayers)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func contains(list []proxy.ServerInfo, b proxy.ServerInfo) bool {
|
||||
for _, as := range list {
|
||||
if as == b {
|
||||
return true
|
||||
}
|
||||
func getEnv(key, fallback string) string {
|
||||
if value, ok := os.LookupEnv(key); ok {
|
||||
return value
|
||||
}
|
||||
return false
|
||||
return fallback
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user