实时
MemFire Cloud提供一个全球分布的实时服务器集群,实现了以下功能:
默认情况下,数据库上的实时处于禁用状态。让我们为todos
表打开实时。
- 转到 应用 中的 Database 页面。
- 单击侧边栏中的 Replication.
- 通过切换Insert, Update和Delete来控制发送的数据库事件。
- 通过选择Source并切换每个表来控制哪些表广播更改。
alter
publication supabase_realtime add table todos;
在客户端中,我们可以监听插入到 todos 表中的任何新数据:
// Initialize the JS client
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY)
// Create a function to handle inserts
const handleInserts = (payload) => {
console.log('Change received!', payload)
}
// Listen to inserts
supabase
.channel('todos')
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'todos' }, handleInserts)
.subscribe()
import 'package:supabase_flutter/supabase_flutter.dart';
void main() async {
// Initialize the Flutter client
Supabase.initialize(
url: 'https://<project>.supabase.co',
anonKey: '<your-anon-key>',
realtimeClientOptions: const RealtimeClientOptions(
eventsPerSecond: 2,
),
);
runApp(const MyApp());
}
final supabase = Supabase.instance.client;
void handleInserts(payload) {
print('Change received! $payload');
}
// Listen to inserts
supabase
.channel('todos')
.onPostgresChanges(
event: PostgresChangeEvent.insert,
schema: 'public',
table: 'todos',
callback: handleInserts)
.subscribe();
使用 subscribe() 侦听数据库更改。
Realtime API 通过 PostgreSQL 的publication功能工作。Postgres 将数据库更改发送到发布
称为supabase_realtime,通过管理此发布,您可以控制广播哪些数据。