Redis
suggest changeRedis is an in-memory key-value data store used widely for caching, session storage, distributed rate limiting, and real-time pub/sub messaging. In server-side Dart (using frameworks such as Shelf, Dart Frog, or Serverpod), you can interact with Redis using the redis package.
Adding the Dependency
Add the redis package to your pubspec.yaml:
dependencies:
redis: ^4.1.0
Run dart pub get to download the package.
Connecting and Basic Key-Value Operations
Use RedisConnection to establish a socket connection and obtain a Command runner:
import 'package:redis/redis.dart';
Future<void> main() async {
final conn = RedisConnection();
try {
// Connect to Redis server on localhost:6379
final Command cmd = await conn.connect('localhost', 6379);
// If authentication is required:
// await cmd.send_object(['AUTH', 'your-redis-password']);
// Set a key with TTL (Time To Live in seconds)
await cmd.send_object(['SET', 'user:session:101', 'token_abc123', 'EX', '3600']);
// Retrieve the value
final session = await cmd.send_object(['GET', 'user:session:101']);
print('Session Token: $session'); // token_abc123
// Check TTL remaining
final ttl = await cmd.send_object(['TTL', 'user:session:101']);
print('Remaining TTL: $ttl seconds');
// Delete a key
final deleted = await cmd.send_object(['DEL', 'user:session:101']);
print('Deleted keys: $deleted');
} finally {
// Always close the connection
await conn.close();
}
}
Working with Hashes
Redis Hashes are ideal for modeling objects without needing to serialize them into JSON strings:
import 'package:redis/redis.dart';
Future<void> manageUserProfile(Command cmd, String userId) async {
final key = 'user:$userId';
// Set multiple fields in a hash
await cmd.send_object([
'HSET',
key,
'username', 'alice',
'email', 'alice@example.com',
'visits', '1'
]);
// Atomically increment a numerical field
final visits = await cmd.send_object(['HINCRBY', key, 'visits', 1]);
print('Updated visits: $visits'); // 2
// Get a single field
final email = await cmd.send_object(['HGET', key, 'email']);
print('Email: $email');
// Get all fields and values
final allData = await cmd.send_object(['HGETALL', key]);
print('User Profile: $allData');
}
Pub/Sub Messaging
Redis provides lightweight publish/subscribe functionality for event broadcasting and real-time chat:
Subscriber
import 'package:redis/redis.dart';
Future<void> startSubscriber() async {
final conn = RedisConnection();
final cmd = await conn.connect('localhost', 6379);
// Wrap connection into a PubSub handler
final pubsub = PubSub(cmd);
pubsub.subscribe(['notifications', 'alerts']);
final stream = pubsub.getStream();
print('Subscribed to channels. Listening for messages...');
await for (final msg in stream) {
// msg is a List: [type, channel, payload]
// type is 'subscribe' for subscription confirmations, 'message' for messages
if (msg[0] != 'message') continue;
final channel = msg[1];
final payload = msg[2];
print('[$channel] Message received: $payload');
}
}
Publisher
import 'package:redis/redis.dart';
Future<void> publishMessage(String channel, String message) async {
final conn = RedisConnection();
final cmd = await conn.connect('localhost', 6379);
try {
final receivers = await cmd.send_object(['PUBLISH', channel, message]);
print('Delivered message to $receivers subscribers.');
} finally {
await conn.close();
}
}
Building a Simple Redis Cache Helper
import 'dart:convert';
import 'package:redis/redis.dart';
class RedisCacheService {
final Command _cmd;
RedisCacheService(this._cmd);
Future<void> setJson(String key, Map<String, dynamic> data, {int ttlSeconds = 300}) async {
final serialized = jsonEncode(data);
await _cmd.send_object(['SET', key, serialized, 'EX', ttlSeconds.toString()]);
}
Future<Map<String, dynamic>?> getJson(String key) async {
final res = await _cmd.send_object(['GET', key]);
if (res == null) return null;
return jsonDecode(res.toString()) as Map<String, dynamic>;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents