DelphiRedisClient - Complete Redis Client Library for Delphi Applications
Quick Answer: DelphiRedisClient is the official Redis client for Delphi. Connect with
TRedisClient.Create('localhost', 6379).Connect, then use&SET/GETfor strings,HSET/HGETfor hashes,LPUSH/RPOPfor lists. Supports pub/sub, transactions, and all Redis features.
What is DelphiRedisClient?
DelphiRedisClient is the official Redis client for Delphi. It provides a complete, type-safe interface to Redis, the popular open-source in-memory data structure store used as database, cache, message broker, and streaming engine.
Whether you need caching, pub/sub messaging, job queues, rate limiting, or real-time analytics, DelphiRedisClient gives you full access to Redis capabilities from your Delphi applications.
Installation
- Download from GitHub
- Add the
sourcesfolder to your Library Path - Add
uses Redis.Client, Redis.Commons;to your unit
Quick Start
Basic Connection and Commands
uses
Redis.Client, Redis.Commons;
var
Redis: IRedisClient;
begin
// Connect to Redis
Redis := TRedisClient.Create('localhost', 6379);
Redis.Connect;
// String operations
Redis.&SET('user:1:name', 'John Doe');
WriteLn(Redis.GET('user:1:name')); // "John Doe"
// Set with expiration (60 seconds)
Redis.SETEX('session:abc123', 60, 'user_data_here');
// Check if key exists
if Redis.EXISTS('user:1:name') then
WriteLn('Key exists');
// Delete key
Redis.DEL(['user:1:name']);
end;
Working with Hashes
// Store user as hash
Redis.HSET('user:1', 'name', 'John Doe');
Redis.HSET('user:1', 'email', 'john@example.com');
Redis.HSET('user:1', 'age', '30');
// Get single field
WriteLn(Redis.HGET('user:1', 'name')); // "John Doe"
// Get all fields
var Fields := Redis.HGETALL('user:1');
// Returns: ['name', 'John Doe', 'email', 'john@example.com', 'age', '30']
// Increment numeric field
Redis.HINCRBY('user:1', 'age', 1); // age is now 31
Working with Lists
// Add to list (queue)
Redis.RPUSH('tasks', ['task1', 'task2', 'task3']);
// Pop from list (FIFO queue)
var Task := Redis.LPOP('tasks'); // "task1"
// Get list length
var Len := Redis.LLEN('tasks'); // 2
// Get range of elements
var Tasks := Redis.LRANGE('tasks', 0, -1); // All elements
Working with Sets
// Add members to set
Redis.SADD('tags:post:1', ['delphi', 'redis', 'tutorial']);
// Check membership
if Redis.SISMEMBER('tags:post:1', 'delphi') then
WriteLn('Post is tagged with delphi');
// Get all members
var Tags := Redis.SMEMBERS('tags:post:1');
// Set operations
Redis.SADD('tags:post:2', ['delphi', 'database', 'orm']);
var CommonTags := Redis.SINTER(['tags:post:1', 'tags:post:2']); // ['delphi']
Working with Sorted Sets
// Leaderboard example
Redis.ZADD('leaderboard', 100, 'player1');
Redis.ZADD('leaderboard', 250, 'player2');
Redis.ZADD('leaderboard', 175, 'player3');
// Get top 3 players (highest scores first)
var TopPlayers := Redis.ZREVRANGE('leaderboard', 0, 2);
// Get player rank
var Rank := Redis.ZREVRANK('leaderboard', 'player2'); // 0 (first place)
// Increment score
Redis.ZINCRBY('leaderboard', 50, 'player1'); // player1 now has 150
Key Features
Data Structures
- Strings - Simple key-value storage with optional expiration
- Hashes - Store objects as field-value pairs
- Lists - Linked lists for queues and stacks
- Sets - Unordered collections of unique strings
- Sorted Sets - Sets ordered by score for leaderboards and priority queues
- Streams - Append-only log data structure
Advanced Features
- Pub/Sub - Real-time messaging between applications
- Transactions - Atomic execution of multiple commands
- Lua Scripting - Server-side scripting for complex operations
- Pipelining - Batch multiple commands for better performance
- Redis Cluster - Support for distributed Redis deployments
Connection Management
- Connection pooling
- Automatic reconnection
- Sentinel support for high availability
- SSL/TLS encryption
Pub/Sub Messaging
Publisher
var Redis := TRedisClient.Create('localhost', 6379);
Redis.Connect;
// Publish message to channel
Redis.PUBLISH('notifications', 'New order received!');
Redis.PUBLISH('notifications', 'Payment processed');
Subscriber
var Redis := TRedisClient.Create('localhost', 6379);
Redis.Connect;
// Subscribe to channel
Redis.SUBSCRIBE(['notifications'],
procedure(Channel, Message: string)
begin
WriteLn(Format('Received on %s: %s', [Channel, Message]));
end
);
Transactions
Execute multiple commands atomically:
// Start transaction
Redis.MULTI;
try
Redis.&SET('key1', 'value1');
Redis.&SET('key2', 'value2');
Redis.INCR('counter');
// Execute all commands atomically
Redis.EXEC;
except
// Discard on error
Redis.DISCARD;
raise;
end;
Caching Patterns
Cache-Aside Pattern
function GetUserFromCache(const UserID: Integer): TUser;
var
CacheKey: string;
CachedData: string;
begin
CacheKey := Format('user:%d', [UserID]);
// Try cache first
CachedData := FRedis.GET(CacheKey);
if CachedData <> '' then
begin
Result := TJson.JsonToObject<TUser>(CachedData);
Exit;
end;
// Cache miss - load from database
Result := FDatabase.GetUser(UserID);
// Store in cache with 5-minute expiration
FRedis.SETEX(CacheKey, 300, TJson.ObjectToJsonString(Result));
end;
Rate Limiting
function IsRateLimited(const ClientIP: string): Boolean;
var
Key: string;
Count: Integer;
begin
Key := Format('ratelimit:%s', [ClientIP]);
// Increment counter
Count := FRedis.INCR(Key);
// Set expiration on first request
if Count = 1 then
FRedis.EXPIRE(Key, 60); // 60-second window
// Allow max 100 requests per minute
Result := Count > 100;
end;
Why Use Redis?
Redis can dramatically improve your application’s performance and capabilities:
| Use Case | Benefit |
|---|---|
| Caching | Reduce database load, sub-millisecond response times |
| Session Storage | Scalable, fast session management |
| Job Queues | Reliable background task processing |
| Rate Limiting | Protect APIs from abuse |
| Real-time Analytics | Count, aggregate, and analyze in real-time |
| Leaderboards | Sorted sets make rankings trivial |
| Pub/Sub Messaging | Real-time notifications between services |
| Distributed Locks | Coordinate between multiple instances |
Delphi Compatibility
| Delphi Version | Supported |
|---|---|
| Delphi 13 Florence | ✅ |
| Delphi 12 Athens | ✅ |
| Delphi 11 Alexandria | ✅ |
| Delphi 10.4 Sydney | ✅ |
| Delphi 10.3 Rio | ✅ |
| Delphi 10.2 Tokyo | ✅ (+ Linux) |
| Delphi 10.1 Berlin | ✅ |
| Delphi 10 Seattle | ✅ |
Platforms: Windows (32/64-bit), Linux (64-bit from Delphi 10.2)
Related Open Source Projects
DelphiRedisClient integrates with other open source projects by the same author:
| Project | Description | Integration |
|---|---|---|
| DMVCFramework | REST API framework for Delphi | Session storage, caching, rate limiting middleware (middleware_ratelimit_redis sample) |
| LoggerPro | Async logging framework | Stream logs to Redis with TLoggerProRedisAppender for centralized logging |
| DelphiGuard | RAII memory management | Automatic cleanup for Redis connections |
Links & Resources
| Resource | Link |
|---|---|
| GitHub Repository | github.com/danieleteti/delphiredisclient |
| Redis Documentation | redis.io/docs |
| Support (Facebook Group) | facebook.com/groups/delphimvcframework |
FAQ: Frequently Asked Questions
What is the best Redis client for Delphi?
DelphiRedisClient is the official and most complete Redis client for Delphi. It supports all Redis data structures, pub/sub, transactions, Lua scripting, and is available through GetIt for easy installation.
How do I connect to Redis from Delphi?
Use DelphiRedisClient:
uses Redis.Client;
var Redis := TRedisClient.Create('localhost', 6379);
Redis.Connect;
Redis.&SET('key', 'value');
Does DelphiRedisClient support Redis Cluster?
Yes, DelphiRedisClient supports Redis Cluster for distributed deployments with automatic slot routing.
How do I implement caching in Delphi?
Use Redis with DelphiRedisClient for high-performance caching:
// Store with expiration
Redis.SETEX('cache:key', 300, 'cached_value'); // 5 minutes
// Retrieve
var Value := Redis.GET('cache:key');
Does DelphiRedisClient support pub/sub?
Yes, full pub/sub support is included. Use PUBLISH to send messages and SUBSCRIBE to receive them in real-time.
How do I use Redis for session storage in Delphi?
Store session data as Redis hashes with expiration:
Redis.HSET('session:abc123', 'user_id', '42');
Redis.HSET('session:abc123', 'username', 'john');
Redis.EXPIRE('session:abc123', 3600); // 1 hour
Can I use Redis transactions in Delphi?
Yes, use MULTI, EXEC, and DISCARD for atomic transactions:
Redis.MULTI;
Redis.&SET('key1', 'value1');
Redis.INCR('counter');
Redis.EXEC;
Does DelphiRedisClient work on Linux?
Yes, DelphiRedisClient supports Linux 64-bit starting from Delphi 10.2 Tokyo.
How do I implement a job queue with Redis in Delphi?
Use Redis lists as queues:
// Producer: add job
Redis.RPUSH('jobs', [JobData]);
// Consumer: get job (blocking)
var Job := Redis.BLPOP(['jobs'], 0); // Wait indefinitely
Is DelphiRedisClient free?
Yes, DelphiRedisClient is free and open-source under the Apache 2.0 license. You can use it in commercial projects without restrictions.
DelphiRedisClient - The official Redis client for Delphi. Complete. Fast. Open-source.
Comments
comments powered by Disqus