-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e43d149
commit 4e774c5
Showing
9 changed files
with
430 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package zcache | ||
|
||
import ( | ||
"github.com/go-redis/redis/v8" | ||
"time" | ||
) | ||
|
||
type Config struct { | ||
Network string | ||
Addr string | ||
Password string | ||
DB int | ||
DialTimeout time.Duration | ||
ReadTimeout time.Duration | ||
WriteTimeout time.Duration | ||
PoolSize int | ||
MinIdleConns int | ||
MaxConnAge time.Duration | ||
PoolTimeout time.Duration | ||
IdleTimeout time.Duration | ||
IdleCheckFrequency time.Duration | ||
} | ||
|
||
func (c *Config) ToRedisConfig() *redis.Options { | ||
return &redis.Options{ | ||
Network: c.Network, | ||
Addr: c.Addr, | ||
Password: c.Password, | ||
DB: c.DB, | ||
DialTimeout: c.DialTimeout, | ||
ReadTimeout: c.ReadTimeout, | ||
WriteTimeout: c.WriteTimeout, | ||
PoolSize: c.PoolSize, | ||
MinIdleConns: c.MinIdleConns, | ||
MaxConnAge: c.MaxConnAge, | ||
PoolTimeout: c.PoolTimeout, | ||
IdleTimeout: c.IdleTimeout, | ||
IdleCheckFrequency: c.IdleCheckFrequency, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
# zcache Package | ||
|
||
## Overview | ||
The `zcache` package provides an abstraction layer over Redis, allowing easy integration of caching mechanisms into Go applications. It simplifies interacting with Redis by offering a common interface for various caching operations. | ||
|
||
## Table of Contents | ||
1. [Features](#features) | ||
2. [Installation](#installation) | ||
3. [Usage](#usage) | ||
4. [Configuration](#configuration) | ||
5. [Mocking Support](#mocking-support) | ||
|
||
## Features | ||
- **Unified Caching Interface**: Offers a consistent API for common caching operations, abstracting the complexity of direct Redis interactions. | ||
- **Distributed Mutex Locks**: Supports distributed synchronization using Redis-based mutex locks, crucial for concurrent operations. | ||
- **Extensibility**: Easy to extend with additional methods for more Redis operations. | ||
- **Serialization and Deserialization**: Automatically handles the conversion of Go data structures to and from Redis storage formats. | ||
- **Mocking for Testing**: Includes mock implementations for easy unit testing without a live Redis instance. | ||
- **Connection Pool Management**: Efficiently handles Redis connection pooling. | ||
- **Supported Operations**: Includes a variety of caching operations like Set, Get, Delete, as well as more advanced operations like Incr, Decr, and others. | ||
|
||
--- | ||
|
||
## Installation | ||
```bash | ||
go get github.com/zondax/golem/pkg/zcache | ||
``` | ||
|
||
--- | ||
|
||
## Usage | ||
|
||
```go | ||
import ( | ||
"github.com/zondax/golem/pkg/zcache" | ||
"context" | ||
"time" | ||
) | ||
|
||
func main() { | ||
config := zcache.Config{Addr: "localhost:6379"} | ||
cache := zcache.NewCache(config) | ||
ctx := context.Background() | ||
|
||
// Set a value | ||
cache.Set(ctx, "key1", "value1", 10*time.Minute) | ||
|
||
// Get a value | ||
if value, err := cache.Get(ctx, "key1"); err == nil { | ||
fmt.Println("Retrieved value:", value) | ||
} | ||
|
||
// Delete a value | ||
cache.Delete(ctx, "key1") | ||
} | ||
``` | ||
|
||
--- | ||
|
||
## Configuration | ||
|
||
Configure zcache using the Config struct, which includes network settings, server address, timeouts, and other connection parameters. This struct allows you to customize the behavior of your cache and mutex instances to fit your application's needs. | ||
|
||
```go | ||
type Config struct { | ||
Addr string // Redis server address | ||
Password string // Redis server password | ||
DB int // Redis database | ||
DialTimeout time.Duration // Timeout for connecting to Redis | ||
ReadTimeout time.Duration // Timeout for reading from Redis | ||
WriteTimeout time.Duration // Timeout for writing to Redis | ||
PoolSize int // Number of connections in the pool | ||
MinIdleConns int // Minimum number of idle connections | ||
IdleTimeout time.Duration // Timeout for idle connections | ||
// Add other configuration fields as needed | ||
} | ||
``` | ||
--- | ||
|
||
## Working with mutex | ||
|
||
```go | ||
func main() { | ||
cache := zcache.NewCache(zcache.Config{Addr: "localhost:6379"}) | ||
mutex := cache.NewMutex("mutex_name", 2*time.Minute) | ||
|
||
// Acquire lock | ||
if err := mutex.Lock(); err != nil { | ||
log.Fatalf("Failed to acquire mutex: %v", err) | ||
} | ||
|
||
// Perform operations under lock | ||
// ... | ||
|
||
// Release lock | ||
if ok, err := mutex.Unlock(); !ok || err != nil { | ||
log.Fatalf("Failed to release mutex: %v", err) | ||
} | ||
} | ||
``` | ||
--- | ||
|
||
## Mocking support | ||
|
||
Use MockZCache and MockZMutex for unit testing. | ||
|
||
```go | ||
func TestCacheOperation(t *testing.T) { | ||
mockCache := new(zcache.MockZCache) | ||
mockCache.On("Get", mock.Anything, "key1").Return("value1", nil) | ||
// Use mockCache in your tests | ||
} | ||
|
||
func TestSomeFunctionWithMutex(t *testing.T) { | ||
mockMutex := new(zcache.MockZMutex) | ||
mockMutex.On("Lock").Return(nil) | ||
mockMutex.On("Unlock").Return(true, nil) | ||
mockMutex.On("Name").Return("myMutex") | ||
|
||
result, err := SomeFunctionThatUsesMutex(mockMutex) | ||
assert.NoError(t, err) | ||
assert.Equal(t, expectedResult, result) | ||
|
||
mockMutex.AssertExpectations(t) | ||
} | ||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
package zcache | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"time" | ||
|
||
"github.com/go-redis/redis/v8" | ||
) | ||
|
||
type redisCache struct { | ||
client *redis.Client | ||
} | ||
|
||
func (c *redisCache) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error { | ||
val, err := json.Marshal(value) | ||
if err != nil { | ||
return err | ||
} | ||
return c.client.Set(ctx, key, val, expiration).Err() | ||
} | ||
|
||
func (c *redisCache) Get(ctx context.Context, key string, data interface{}) error { | ||
val, err := c.client.Get(ctx, key).Result() | ||
if err != nil { | ||
return err | ||
} | ||
return json.Unmarshal([]byte(val), &data) | ||
} | ||
|
||
func (c *redisCache) Delete(ctx context.Context, key string) error { | ||
return c.client.Del(ctx, key).Err() | ||
} | ||
|
||
func (c *redisCache) Exists(ctx context.Context, keys ...string) (int64, error) { | ||
return c.client.Exists(ctx, keys...).Result() | ||
} | ||
|
||
func (c *redisCache) Incr(ctx context.Context, key string) (int64, error) { | ||
return c.client.Incr(ctx, key).Result() | ||
} | ||
|
||
func (c *redisCache) Decr(ctx context.Context, key string) (int64, error) { | ||
return c.client.Decr(ctx, key).Result() | ||
} | ||
|
||
func (c *redisCache) FlushAll(ctx context.Context) error { | ||
return c.client.FlushAll(ctx).Err() | ||
} | ||
|
||
func (c *redisCache) LPush(ctx context.Context, key string, values ...interface{}) (int64, error) { | ||
return c.client.LPush(ctx, key, values...).Result() | ||
} | ||
|
||
func (c *redisCache) RPush(ctx context.Context, key string, values ...interface{}) (int64, error) { | ||
return c.client.RPush(ctx, key, values...).Result() | ||
} | ||
|
||
func (c *redisCache) SMembers(ctx context.Context, key string) ([]string, error) { | ||
return c.client.SMembers(ctx, key).Result() | ||
} | ||
|
||
func (c *redisCache) SAdd(ctx context.Context, key string, members ...interface{}) (int64, error) { | ||
return c.client.SAdd(ctx, key, members...).Result() | ||
} | ||
|
||
func (c *redisCache) HSet(ctx context.Context, key string, values ...interface{}) (int64, error) { | ||
return c.client.HSet(ctx, key, values...).Result() | ||
} | ||
|
||
func (c *redisCache) HGet(ctx context.Context, key, field string) (string, error) { | ||
return c.client.HGet(ctx, key, field).Result() | ||
} |
Oops, something went wrong.