Redis Package
This package provides Redis client functionality for the Tender Management system, specifically designed for token blacklisting and caching operations.
Features
- Connection Management: Handles Redis client connections with proper error handling
- Interface-based Design: Uses interfaces for easy testing and mocking
- Configuration Support: Supports Redis configuration from environment variables
- Connection Testing: Validates connections on startup
- Resource Cleanup: Proper connection closing and cleanup
Usage
Basic Setup
import "tm/pkg/redis"
// Create Redis configuration
config := &redis.Config{
Host: "localhost",
Port: 6379,
Password: "password",
DB: 0,
PoolSize: 10,
}
// Create Redis client
client, err := redis.NewClient(config, logger)
if err != nil {
log.Fatal(err)
}
defer client.Close()
// Use the client
err = client.Set(ctx, "key", "value", time.Hour)
Token Blacklisting
The Redis client is primarily used for JWT token blacklisting:
// Add token to blacklist
err = client.Set(ctx, "blacklist:token_hash", "1", tokenExpiration)
// Check if token is blacklisted
exists, err := client.Exists(ctx, "blacklist:token_hash")
if err != nil {
// Handle error
}
if exists > 0 {
// Token is blacklisted
}
Configuration
The Redis configuration supports the following fields:
Host: Redis server hostname (default: localhost)Port: Redis server port (default: 6379)Password: Redis authentication passwordDB: Redis database number (default: 0)PoolSize: Connection pool size (default: 10)
Environment Variables
The configuration can be loaded from environment variables:
TM_CACHE_REDIS_HOSTTM_CACHE_REDIS_PORTTM_CACHE_REDIS_PASSWORDTM_CACHE_REDIS_DBTM_CACHE_REDIS_POOL_SIZE
Error Handling
The package provides comprehensive error handling:
- Connection failures are logged with context
- All Redis operations return proper errors
- Connection timeouts are handled gracefully
- Resource cleanup is guaranteed with defer statements
Testing
The interface-based design makes it easy to mock Redis operations in tests:
type MockRedisClient struct {
// Implement the Client interface
}
// Use in tests
client := &MockRedisClient{}
Dependencies
github.com/redis/go-redis/v9: Redis client librarytm/pkg/logger: Logging interface