db.redis #
Redis Client for V
This module provides a Redis client implementation in V that supports the Redis Serialization Protocol (RESP) versions 2 (RESP2) and 3 (RESP3) with a type-safe interface for common Redis commands.
Features
- Type-Safe Commands: Auto-detects value types at compile time
- Pipeline Support: Group commands for batch execution
- Connection Pooling: Efficient resource management
- RESP Protocol Support: Full Redis Serialization Protocol implementation
- Memory Efficient: Pre-allocated buffers for minimal allocations
Quick Start
module main
import db.redis
fn main() {
// Connect to Redis
// Uncomment passwod line if authentication is needed
mut db := redis.connect(redis.Config{
// Available Config options (none of which need to be specified if you want the defauilts):
// host: 'localhost' - default
// password: 'your_password' - no default, you need to supply password if your redis server
// is set up to need one
// port: 6379 - default
// tls: false - default, set to true for ssl connection
})!
println('Server supports RESP${db.version} protocol')
// Set and get values
db.set('name', 'Alice')!
name := db.get[string]('name')!
println('Name: ${name}') // Output: Name: Alice
// Integer operations
db.set('counter', 42)!
db.incr('counter')!
counter := db.get[int]('counter')!
println('Counter: ${counter}') // Output: Counter: 43
// Clean up
db.close()!
}
Supported Commands
Key Operations
// Set value
db.set('key', 'value')!
db.set('number', 42)!
db.set('binary', []u8{len: 4, init: 0})!
// Get value
str_value := db.get[string]('key')!
int_value := db.get[int]('number')!
bin_value := db.get[[]u8]('binary')!
// Delete key
db.del('key')!
// Set expiration
db.expire('key', 60)! // 60 seconds
Hash Operations
// Set hash fields
db.hset('user:1', {
'name': 'Bob',
'age': '30',
})!
// Get single field
name := db.hget[string]('user:1', 'name')!
// Get all fields
user_data := db.hgetall[string]('user:1')!
println(user_data) // Output: {'name': 'Bob', 'age': '30'}
Pipeline Operations
// Start pipeline
db.pipeline_start()
// Queue commands
db.incr('counter')!
db.set('name', 'Charlie')!
db.get[string]('name')!
// Execute and get responses
responses := db.pipeline_execute()!
for resp in responses {
println(resp)
}
Custom Commands
// Run raw commands
resp := db.cmd('SET', 'custom', 'value')!
result := db.cmd('GET', 'custom')!
// Complex commands
db.cmd('HSET', 'user:2', 'field1', 'value1', 'field2', '42')!
Error Handling
All functions return ! types and will return detailed errors for:
- Connection issues
- Protocol violations
- Type mismatches
- Redis error responses
- Timeout conditions
result := db.get[string]('nonexistent') or {
println('Key not found')
return
}
Connection Management
config := redis.Config{
host: 'redis.server'
port: 6379
}
mut db := redis.connect(config)!
defer {
db.close() or { eprintln('Error closing connection: ${err}') }
}
Performance Tips
- Reuse Connections: Maintain connections instead of creating new ones
- Use Pipelines: Batch commands for high-throughput operations
- Prefer Integers: Use numeric types for counters and metrics
- Specify Types: Always specify return types for get operations
fn connect #
fn connect(config Config) !DB
connect establishes a connection to a Redis server
type RedisValue #
type RedisValue = bool
| big.Integer
| f32
| f64
| i64
| []u8
| RedisBlobError
| RedisMap
| RedisNull
| RedisPush
| RedisSet
| map[string]RedisValue
| []RedisValue
| RedisVerbatim
| string
RedisValue represents all possible RESP (Redis Serialization Protocol) data types
struct Config #
struct Config {
pub mut:
host string = '127.0.0.1' // Redis server host
port u16 = 6379 // Redis server port
password string // Redis server password (optional)
tls bool // Enable TLS/SSL connection
version int @[deprecated] // ignored - RESP version auto handled in connect
}
Configuration options for Redis connection
struct DB #
struct DB {
pub mut:
version int // RESP protocol version
conn &net.TcpConn = unsafe { nil } // TCP connection to Redis
ssl_conn &ssl.SSLConn = unsafe { nil } // SSL connection to Redis
tls bool
// Pre-allocated buffers to reduce memory allocations
cmd_buf []u8 // Buffer for building commands
resp_buf []u8 // Buffer for reading responses
pipeline_mode bool
pipeline_buffer []u8
pipeline_cmd_count int
}
DB represents a Redis database connection
fn (DB) close #
fn (mut db DB) close() !
close terminates the connection to Redis server
fn (DB) auth #
fn (mut db DB) auth(password string) !
auth sends an AUTH command to the server with the given password.
fn (DB) ping #
fn (mut db DB) ping() !string
ping sends a PING command to verify server responsiveness
fn (DB) del #
fn (mut db DB) del(key string) !i64
del deletes a key
fn (DB) set #
fn (mut db DB) set[T](key string, value T) !string
set stores a key-value` pair in Redis. Supported value types: number, string, []u8
fn (DB) get #
fn (mut db DB) get[T](key string) !T
get retrieves the value of a key. Supported return types: string, int, []u8
fn (DB) incr #
fn (mut db DB) incr(key string) !i64
incr increments the integer value of a key by 1
fn (DB) decr #
fn (mut db DB) decr(key string) !i64
decr decrements the integer value of a key by 1
fn (DB) hset #
fn (mut db DB) hset[T](key string, m map[string]T) !int
hset sets multiple key-value pairs in a hash. Supported value types: string, int, []u8
fn (DB) hget #
fn (mut db DB) hget[T](key string, m_key string) !T
hget retrieves the value of a hash field. Supported return types: string, int, []u8
fn (DB) hgetall #
fn (mut db DB) hgetall[T](key string) !map[string]T
hgetall retrieves all fields and values of a hash. Supported value types: string, int, []u8
fn (DB) expire #
fn (mut db DB) expire(key string, seconds int) !bool
expire sets a key's time to live in seconds
fn (DB) cmd #
fn (mut db DB) cmd(cmd ...string) !RedisValue
cmd sends a custom command to Redis server for example: db.cmd('SET', 'key', 'value')!
fn (DB) pipeline_start #
fn (mut db DB) pipeline_start()
pipeline_start start a new pipeline
fn (DB) pipeline_execute #
fn (mut db DB) pipeline_execute() ![]RedisValue
pipeline_execute executes the cmds in pipeline at once and retrieves all responses
struct RedisBlobError #
struct RedisBlobError {
pub:
data []u8
}
RESP3 wrapper types
struct RedisMap #
struct RedisMap {
pub:
// interleaved key/value pairs: [k1, v1, k2, v2, ...]
pairs []RedisValue
}
struct RedisNull #
struct RedisNull {}
RedisNull represents the Redis NULL type
struct RedisPush #
struct RedisPush {
pub:
elements []RedisValue
}
struct RedisSet #
struct RedisSet {
pub:
elements []RedisValue
}
struct RedisVerbatim #
struct RedisVerbatim {
pub:
format string
data []u8
}