Why Switching from Java to Go Simplifies Redis Integration – A Hands‑On Guide
This article walks through the author’s decision to continue learning Go for Redis access, outlines a step‑by‑step study plan, compares Go and Java Redis clients, presents a custom Go‑Redis wrapper with full source code, demonstrates usage in unit tests, and shares console output observations.
Learning Path and Motivation
The author initially considered abandoning Go but decided to persist, mainly because a Java‑based Redis client needed to be migrated to Go. The study plan includes three stages: basic Redis connection and operations, collection commands (hash, list, set, sorted set), and Redis streams.
Dependencies
The Go project uses the standard go.mod file and imports the github.com/go-redis/redis library (v6.15.9+incompatible), which provides a built‑in connection pool.
Redis API Wrapper
A thin wrapper named RedisBase is defined to encapsulate common Redis actions while handling default return values and error logging. Key methods include: NewRdisPool(host string, db int) RedisBase – creates a client with a pool size of 200 and various timeout settings. Ping() string – checks connectivity. Keys(patten string) []string – retrieves keys matching a pattern.
Set(key string, value interface{}, second time.Duration) string– sets a key with optional expiration. Get(key string) string – fetches a key’s value. GetSet(key string, value interface{}) string – atomically sets a new value and returns the old one. SetNX(key string, value interface{}, second int64) bool – sets a key only if it does not exist. MGet(keys ...string) []interface{} – batch retrieval. MSet(keys ...string) string – batch setting. Incr(key string) int64 and IncrBy(key string, value int64) int64 – increment operations. Decr(key string) int64 and DecrBy(key string, value int64) int64 – decrement operations. Del(keys ...string) int64 – deletes one or more keys. Expire(key string, second int64) bool – sets a TTL in seconds.
package redis
import (
"fmt"
"log"
"time"
"github.com/go-redis/redis"
"funtester/base"
)
type RedisBase struct {
Host string
db int
pool *redis.Client
}
func NewRdisPool(host string, db int) RedisBase {
redisBase := RedisBase{Host: host, db: db}
redisBase.pool = redis.NewClient(&redis.Options{
Addr: host,
DB: 0,
MaxRetries: 3,
MinRetryBackoff: 100 * time.Millisecond,
DialTimeout: 5 * time.Second,
WriteTimeout: 1 * time.Second,
PoolSize: 200,
MaxConnAge: 10 * time.Second,
IdleTimeout: 8 * time.Second,
})
_, err := redisBase.pool.Ping().Result()
if err != nil {
log.Fatal("connection failed", err)
}
log.Println("Redis connection successful")
return redisBase
}
func (r RedisBase) Ping() string {
result, err := r.pool.Ping().Result()
if err != nil {
log.Println("ping failed")
}
return result
}
// Additional methods (Keys, Set, Get, GetSet, SetNX, MGet, MSet, Incr, IncrBy, Decr, DecrBy, Del, Expire) follow the same pattern, logging errors and returning appropriate values.API Demonstration
A simple test file shows how to use the wrapper in practice. It creates a pool, performs set/get, GetSet, batch operations, increments, TTL settings, and key deletions, logging each step.
package test
import (
"funtester/db/redis"
"funtester/ftool"
"github.com/go-playground/assert/v2"
"log"
"strconv"
"testing"
)
var pool = redis.NewRdisPool("127.0.0.1:6379", 1)
func TestRedis(t *testing.T) {
var str = "FunTester"
set := pool.Set("fun", str, 0)
log.Print(set)
get := pool.Get("fun")
assert.Equal(t, get, str)
getSet := pool.GetSet("fun", str+ftool.RandomStr(3))
log.Println(getSet)
// Additional operations: MGet, MSet, Incr, IncrBy, Expire, Keys, SetNX, Del, etc.
}Console Output
The test run prints connection success messages, the stored value, index/value pairs from batch gets, key listings, and the results of increment/decrement operations. The output is intentionally simple, highlighting that the wrapper behaves similarly to the Java version while being more concise.
2022/06/18 21:31:06 Redis connection successful
2022/06/18 21:31:06 connection confirmed!
=== RUN TestRedis
2022/06/18 21:31:06 OK
2022/06/18 21:31:06 FunTester
2022/06/18 21:31:06 index :0 value : FunTesterc3F
2022/06/18 21:31:06 index :1 value : 32342
... (additional log lines) ...
--- PASS: TestRedis (0.00s)
PASSObservations
The Go client feels more succinct than the Java counterpart, largely because it includes a built‑in connection pool and requires less boilerplate. The author plans to extend the wrapper with performance benchmarks once the tutorial is complete.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
