Flutter Redis数据库交互插件redis的使用
Flutter Redis数据库交互插件redis的使用
简介
redis-dart
是一个用于 Dart 的 Redis 客户端库。它支持 Redis 协议解析,并且设计简单、快速,无需任何外部依赖即可运行。
支持的功能
- 事务 和 CAS(Check-and-Set) 模式
- 发布/订阅 功能
- Unicode 支持
- 性能 和 简洁性
- TLS 支持
简单示例
连接和设置键值
import 'package:redis/redis.dart';
void main() async {
final conn = RedisConnection();
await conn.connect('localhost', 6379).then((Command command) {
command.send_object(["SET", "key", "0"]).then((var response) {
print(response); // 输出: OK
});
});
}
顺序执行命令
import 'package:redis/redis.dart';
void main() async {
final conn = RedisConnection();
await conn.connect('localhost', 6379).then((Command command) {
command.send_object(["SET", "key", "0"]).then((var response) {
assert(response == 'OK');
return command.send_object(["INCR", "key"]);
}).then((var response) {
assert(response == 1);
return command.send_object(["INCR", "key"]);
}).then((var response) {
assert(response == 2);
return command.send_object(["INCR", "key"]);
}).then((var response) {
assert(response == 3);
return command.send_object(["GET", "key"]);
}).then((var response) {
print(response); // 输出: 3
});
});
}
并行执行命令
import 'package:redis/redis.dart';
void main() async {
final conn = RedisConnection();
await conn.connect('localhost', 6379).then((Command command) {
command.send_object(["SET", "key", "0"]).then((var response) {
assert(response == 'OK');
});
command.send_object(["INCR", "key"]).then((var response) {
assert(response == 1);
});
command.send_object(["INCR", "key"]).then((var response) {
assert(response == 2);
});
command.send_object(["INCR", "key"]).then((var response) {
assert(response == 3);
});
command.send_object(["GET", "key"]).then((var response) {
print(response); // 输出: 3
});
});
}
泛型支持
Redis 响应和请求可以任意嵌套。以下是 Redis 和 Dart 之间的映射关系:
Redis | Dart |
---|---|
String | String |
Integer | Integer |
Array | List |
Error | RedisError |
Bulk | String 或 Binary |
示例
import 'package:redis/redis.dart';
void main() async {
final conn = RedisConnection();
await conn.connect('localhost', 6379).then((Command command) {
command.send_object(["EVAL", "return {KEYS[1],{KEYS[2],{ARGV[1]},ARGV[2]},2}", "2", "key1", "key2", "first", "second"]).then((response) {
print(response); // 输出: [key1, [key2, [first], second], 2]
});
});
}
TLS 支持
import 'package:redis/redis.dart';
void main() async {
final conn = RedisConnection();
await conn.connectSecure('localhost', 6379).then((Command command) {
command.send_object(["AUTH", "username", "password"]).then((var response) {
print(response);
command.send_object(["SET", "key", "0"]).then((var response) {
print(response); // 输出: OK
});
});
});
}
性能测试
import 'package:redis/redis.dart';
void main() async {
const int N = 200000;
int start;
final conn = RedisConnection();
await conn.connect('localhost', 6379).then((Command command) {
print("test started, please wait ...");
start = DateTime.now().millisecondsSinceEpoch;
command.pipe_start();
command.send_object(["SET", "test", "0"]);
for (int i = 1; i <= N; i++) {
command.send_object(["INCR", "test"]).then((v) {
if (i != v) throw("wrong received value, we got $v");
});
}
command.send_object(["GET", "test"]).then((v) {
print(v);
double diff = (DateTime.now().millisecondsSinceEpoch - start) / 1000.0;
double perf = N / diff;
print("$N operations done in $diff s\nperformance $perf/s");
});
command.pipe_end();
});
}
事务支持
示例
import 'package:redis/redis.dart';
void main() async {
final conn = RedisConnection();
await conn.connect('localhost', 6379).then((Command command) {
command.multi().then((Transaction trans) {
trans.send_object(["SET", "val", "0"]);
for (int i = 0; i < 200000; ++i) {
trans.send_object(["INCR", "val"]).then((v) {
assert(i == v);
});
}
trans.send_object(["GET", "val"]).then((v) {
print("number is now $v");
});
trans.exec();
});
});
}
CAS 支持
示例
import 'package:redis/redis.dart';
void main() async {
final conn = RedisConnection();
await conn.connect('localhost', 6379).then((Command command) {
Cas cas = Cas(command);
cas.watch(["key"], () {
command.send_object(["GET", "key"]).then((String val) {
int i = int.parse(val);
i++;
cas.multiAndExec((Transaction trans) {
trans.send_object(["SET", "key", i.toString()]);
});
});
});
});
}
Unicode 支持
默认情况下,字符串使用 UTF8 编码/解码。每个字符串都会被转换为二进制数组,使用 UTF8 编码。
二进制数据支持
import 'package:redis/redis.dart';
void main() async {
final conn = RedisConnection();
Command cmd = await conn.connect('localhost', 6379);
Command cmd_bin = Command.from(cmd).setParser(RedisParserBulkBinary());
List<int> d = [1, 2, 3, 4, 5, 6, 7, 8, 9];
await cmd_bin.send_object(["SET", "key", RedisBulk(d)]);
var r = await cmd_bin.send_object(["GET", "key"]);
print(r); // 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]
}
发布/订阅支持
订阅消息
import 'dart:async';
import 'package:redis/redis.dart';
Future<void> rx() async {
Command cmd = await RedisConnection().connect('localhost', 6379);
final pubsub = PubSub(cmd);
pubsub.subscribe(["monkey"]);
final stream = pubsub.getStream();
var streamWithoutErrors = stream.handleError((e) => print("error $e"));
await for (final msg in streamWithoutErrors) {
var kind = msg[0];
var food = msg[2];
if (kind == "message") {
print("monkey got ${food}");
if (food == "cucumber") {
print("monkey does not like cucumber");
cmd.get_connection().close();
}
} else {
print("received non-message ${msg}");
}
}
}
Future<void> tx() async {
Command cmd = await RedisConnection().connect('localhost', 6379);
await cmd.send_object(["PUBLISH", "monkey", "banana"]);
await cmd.send_object(["PUBLISH", "monkey", "apple"]);
await cmd.send_object(["PUBLISH", "monkey", "peanut"]);
await cmd.send_object(["PUBLISH", "monkey", "cucumber"]);
cmd.get_connection().close();
}
void main() async {
var frx = rx();
var ftx = tx();
await ftx;
await frx;
}
发送消息
import 'package:redis/redis.dart';
void main() async {
Command cmd = await RedisConnection().connect('localhost', 6379);
await cmd.send_object(["PUBLISH", "monkey", "banana"]);
}
待办事项
- 更好的文档
- 实现所有“通用命令”的命名命令
- 更好的错误处理能力
- 代码拼写检查
变更日志
详见 CHANGELOG.md
希望这些示例和说明能帮助你在 Flutter 项目中使用 redis-dart
插件与 Redis 数据库进行交互。如果有任何问题或需要进一步的帮助,请随时提问!
更多关于Flutter Redis数据库交互插件redis的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复