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.
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()!
}
// 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
// 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'}
// 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)
}
// 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')!
All functions return ! types and will return detailed errors for:
result := db.get[string]('nonexistent') or {
println('Key not found')
return
}
config := redis.Config{
host: 'redis.server'
port: 6379
}
mut db := redis.connect(config)!
defer {
db.close() or { eprintln('Error closing connection: ${err}') }
}
redis.DB also implements pool.ConnectionPoolable, so it can be used
directly with vlib/pool connection pools.