add Valkey configuration and connection management

This commit is contained in:
pigwin
2025-01-06 20:47:55 +00:00
parent c456bdecdb
commit c6fc0070cf
7 changed files with 163 additions and 1 deletions

View File

@@ -7,5 +7,11 @@
"dbname": "ti1", "dbname": "ti1",
"sslmode": "disable" "sslmode": "disable"
}, },
"valkey": {
"host": "127.0.0.1",
"port": "6379",
"max_conns": 50,
"timeout_ms": 5000
},
"temp": "value" "temp": "value"
} }

View File

@@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"os" "os"
"strconv"
) )
type Config struct { type Config struct {
@@ -15,6 +16,12 @@ type Config struct {
DBName string `json:"dbname"` DBName string `json:"dbname"`
SSLMode string `json:"sslmode"` SSLMode string `json:"sslmode"`
} `json:"database"` } `json:"database"`
Valkey struct {
Host string `json:"host"`
Port string `json:"port"`
MaxConns int `json:"max_conns"`
TimeoutMs int `json:"timeout_ms"`
} `json:"valkey"`
Temp string `json:"temp"` Temp string `json:"temp"`
} }
@@ -53,7 +60,24 @@ func LoadConfig(file string) (Config, error) {
if temp := os.Getenv("TEMP"); temp != "" { if temp := os.Getenv("TEMP"); temp != "" {
config.Temp = temp config.Temp = temp
} }
//log.Println("Temp value:", config.Temp)
// Override Valkey settings with environment variables
if valkeyHost := os.Getenv("VALKEY_HOST"); valkeyHost != "" {
config.Valkey.Host = valkeyHost
}
if valkeyPort := os.Getenv("VALKEY_PORT"); valkeyPort != "" {
config.Valkey.Port = valkeyPort
}
if maxConns := os.Getenv("VALKEY_MAX_CONNS"); maxConns != "" {
if val, err := strconv.Atoi(maxConns); err == nil {
config.Valkey.MaxConns = val
}
}
if timeoutMs := os.Getenv("VALKEY_TIMEOUT_MS"); timeoutMs != "" {
if val, err := strconv.Atoi(timeoutMs); err == nil {
config.Valkey.TimeoutMs = val
}
}
return config, nil return config, nil
} }

93
config/valkey.go Normal file
View File

@@ -0,0 +1,93 @@
package config
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"time"
"github.com/valkey-io/valkey-go"
)
type ValkeyConfig struct {
Host string `json:"host"`
Port string `json:"port"`
MaxConns int `json:"max_conns"`
TimeoutMs int `json:"timeout_ms"`
}
func LoadValkeyConfig(file string) (ValkeyConfig, error) {
var config ValkeyConfig
configFile, err := os.Open(file)
if err != nil {
return config, fmt.Errorf("failed to open config file: %w", err)
}
defer configFile.Close()
if err := json.NewDecoder(configFile).Decode(&config); err != nil {
return config, fmt.Errorf("failed to parse Valkey config: %w", err)
}
// Override with environment variables if set
if host := os.Getenv("VALKEY_HOST"); host != "" {
config.Host = host
}
if port := os.Getenv("VALKEY_PORT"); port != "" {
config.Port = port
}
if maxConns := os.Getenv("VALKEY_MAX_CONNS"); maxConns != "" {
if val, err := strconv.Atoi(maxConns); err == nil {
config.MaxConns = val
}
}
if timeoutMs := os.Getenv("VALKEY_TIMEOUT_MS"); timeoutMs != "" {
if val, err := strconv.Atoi(timeoutMs); err == nil {
config.TimeoutMs = val
}
}
return config, nil
}
func ConnectToValkey(configPath string) (valkey.Client, error) {
fmt.Println("Loading Valkey configuration...")
valkeyConfig, err := LoadValkeyConfig(configPath)
if err != nil {
return nil, fmt.Errorf("failed to load Valkey config: %v", err)
}
fmt.Println("Valkey configuration loaded successfully!")
// Setup Valkey client options
options := valkey.ClientOption{
InitAddress: []string{fmt.Sprintf("%s:%s", valkeyConfig.Host, valkeyConfig.Port)},
// Additional options can be added here if required
}
fmt.Printf("Connecting to Valkey at %s:%s...\n", valkeyConfig.Host, valkeyConfig.Port)
client, err := valkey.NewClient(options)
if err != nil {
return nil, fmt.Errorf("failed to connect to Valkey: %v", err)
}
// Optionally, perform a ping to validate the connection
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(valkeyConfig.TimeoutMs))
defer cancel()
if err := client.Do(ctx, client.B().Ping().Build()).Error(); err != nil {
client.Close()
return nil, fmt.Errorf("failed to ping Valkey: %v", err)
}
log.Println("Connected to Valkey successfully!")
return client, nil
}
func DisconnectFromValkey(client valkey.Client) error {
fmt.Println("Disconnecting from Valkey...")
client.Close()
log.Println("Disconnected from Valkey successfully!")
return nil
}

View File

@@ -26,6 +26,10 @@ func InsertOrUpdateEstimatedCall(db *sql.DB, values []interface{}) (int, string,
hashString := hex.EncodeToString(hash[:]) hashString := hex.EncodeToString(hash[:])
println(hashString) println(hashString)
estimatedVehicleJourneyID := values[0]
orderID := values[1]
fmt.Printf("Estimated Vehicle Journey ID: %v, Order ID: %v\n", estimatedVehicleJourneyID, orderID)
query := ` query := `
INSERT INTO calls ( INSERT INTO calls (
estimatedvehiclejourney, "order", stoppointref, estimatedvehiclejourney, "order", stoppointref,

5
go.mod
View File

@@ -3,3 +3,8 @@ module ti1
go 1.23.4 go 1.23.4
require github.com/lib/pq v1.10.9 require github.com/lib/pq v1.10.9
require (
github.com/valkey-io/valkey-go v1.0.52 // indirect
golang.org/x/sys v0.24.0 // indirect
)

4
go.sum
View File

@@ -1,2 +1,6 @@
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/valkey-io/valkey-go v1.0.52 h1:ojrR736satGucqpllYzal8fUrNNROc11V10zokAyIYg=
github.com/valkey-io/valkey-go v1.0.52/go.mod h1:BXlVAPIL9rFQinSFM+N32JfWzfCaUAqBpZkc4vPY6fM=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

26
valkey/commands.go Normal file
View File

@@ -0,0 +1,26 @@
package valkey
import (
"context"
"fmt"
"github.com/valkey-io/valkey-go"
)
func SetValkeyValue(client valkey.Client, key, value string) error {
ctx := context.Background()
err := client.Do(ctx, client.B().Set().Key(key).Value(value).Build()).Error()
if err != nil {
return fmt.Errorf("failed to set value in Valkey: %v", err)
}
return nil
}
func GetValkeyValue(client valkey.Client, key string) (string, error) {
ctx := context.Background()
value, err := client.Do(ctx, client.B().Get().Key(key).Build()).ToString()
if err != nil {
return "", fmt.Errorf("failed to get value from Valkey: %v", err)
}
return value, nil
}