Skip to content
Realtime

实时入门

Learn how to build real-time applications with Supabase Realtime

快速开始 #

🌐 Quick start

1. 安装客户端库 #

🌐 1. Install the client library

1
npm install @supabase/supabase-js

2. 初始化客户端 #

🌐 2. Initialize the client

获取你的项目 URL 和密钥。

获取 API 详情 #

🌐 Get API details

要与数据库表中的数据进行交互,你可以使用封装了自动生成的数据 API 端点的客户端库,并使用来自项目 Connect 对话框的项目 URL 和密钥进行认证。

🌐 To interact with data in database tables, you use the client libraries that wrap the auto-generated Data API endpoints, authenticating using the Project URL and key from the project Connect dialog.

Project URL
Publishable key
1
import { createClient } from '@supabase/supabase-js'
2
3
const supabase = createClient('https://<project>.supabase.co', '<sb_publishable_key>')

3. 创建你的第一个通道 #

🌐 3. Create your first Channel

通道是实时功能的基础。可以把它们想象成客户端可以交流的房间。每个通道都有一个主题名称,并且会标明是公共的还是私有的。

🌐 Channels are the foundation of Realtime. Think of them as rooms where clients can communicate. Each channel is identified by a topic name and if they are public or private.

1
// Create a channel with a descriptive topic name
2
const channel = supabase.channel('room:lobby:messages', {
3
config: { private: true }, // Recommended for production
4
})

4. 设置授权 #

🌐 4. Set up authorization

既然我们使用的是私有通道,你需要在 realtime.messages 表上创建一个基本的 RLS 策略,以允许已认证的用户连接。行级安全 (RLS) 策略根据用户认证和自定义规则来控制谁可以访问你的实时通道:

🌐 Since we're using a private channel, you need to create a basic RLS policy on the realtime.messages table to allow authenticated users to connect. Row Level Security (RLS) policies control who can access your Realtime channels based on user authentication and custom rules:

1
-- Allow authenticated users to receive broadcasts
2
CREATE POLICY "authenticated_users_can_receive" ON realtime.messages
3
FOR SELECT TO authenticated USING (true);
4
5
-- Allow authenticated users to send broadcasts
6
CREATE POLICY "authenticated_users_can_send" ON realtime.messages
7
FOR INSERT TO authenticated WITH CHECK (true);

5. 发送和接收消息 #

🌐 5. Send and receive messages

使用 Realtime 发送消息主要有三种方式:

🌐 There are three main ways to send messages with Realtime:

5.1 使用客户端库 #

🌐 5.1 using client libraries

使用 Supabase 客户端发送和接收消息:

🌐 Send and receive messages using the Supabase client:

1
// Listen for messages
2
channel
3
.on('broadcast', { event: 'message_sent' }, (payload: { payload: any }) => {
4
console.log('New message:', payload.payload)
5
})
6
.subscribe()
7
8
// Send a message
9
channel.send({
10
type: 'broadcast',
11
event: 'message_sent',
12
payload: {
13
text: 'Hello, world!',
14
user: 'john_doe',
15
timestamp: new Date().toISOString(),
16
},
17
})

5.2 使用 HTTP/REST API #

🌐 5.2 using HTTP/REST API

通过 HTTP 请求发送消息,非常适合服务器端应用:

🌐 Send messages via HTTP requests, perfect for server-side applications:

1
// Send message via REST API
2
const response = await fetch(`https://<project>.supabase.co/rest/v1/rpc/broadcast`, {
3
method: 'POST',
4
headers: {
5
'Content-Type': 'application/json',
6
-H "apikey: <SECRET_KEY>"
7
},
8
body: JSON.stringify({
9
topic: 'room:lobby:messages',
10
event: 'message_sent',
11
payload: {
12
text: 'Hello from server!',
13
user: 'system',
14
timestamp: new Date().toISOString(),
15
},
16
private: true,
17
}),
18
})

5.3 使用数据库触发器 #

🌐 5.3 using database triggers

使用触发器自动广播数据库更改。选择最适合你需求的方法:

🌐 Automatically broadcast database changes using triggers. Choose the approach that best fits your needs:

使用 realtime.broadcast_changes(最适合镜像数据库更改)

1
-- Create a trigger function for broadcasting database changes
2
CREATE OR REPLACE FUNCTION broadcast_message_changes()
3
RETURNS TRIGGER AS $$
4
BEGIN
5
-- Broadcast to room-specific channel
6
PERFORM realtime.broadcast_changes(
7
'room:' || NEW.room_id::text || ':messages',
8
TG_OP,
9
TG_OP,
10
TG_TABLE_NAME,
11
TG_TABLE_SCHEMA,
12
NEW,
13
OLD
14
);
15
RETURN NULL;
16
END;
17
$$ LANGUAGE plpgsql SECURITY DEFINER;
18
19
-- Apply trigger to your messages table
20
CREATE TRIGGER messages_broadcast_trigger
21
AFTER INSERT OR UPDATE OR DELETE ON messages
22
FOR EACH ROW EXECUTE FUNCTION broadcast_message_changes();

使用 realtime.send(最适合自定义通知和筛选数据)

1
-- Create a trigger function for custom notifications
2
CREATE OR REPLACE FUNCTION notify_message_activity()
3
RETURNS TRIGGER AS $$
4
BEGIN
5
-- Send custom notification when new message is created
6
IF TG_OP = 'INSERT' THEN
7
PERFORM realtime.send(
8
jsonb_build_object(
9
'message_id', NEW.id,
10
'user_id', NEW.user_id,
11
'room_id', NEW.room_id,
12
'created_at', NEW.created_at
13
),
14
'message_created',
15
'room:' || NEW.room_id::text || ':notifications',
16
true -- private channel
17
);
18
END IF;
19
20
RETURN NULL;
21
END;
22
$$ LANGUAGE plpgsql SECURITY DEFINER;
23
24
-- Apply trigger to your messages table
25
CREATE TRIGGER messages_notification_trigger
26
AFTER INSERT ON messages
27
FOR EACH ROW EXECUTE FUNCTION notify_message_activity();
  • realtime.broadcast_changes 发送带有元数据的完整数据库更改
  • realtime.send 让你可以发送自定义数据包,并精确控制广播的数据内容

基本最佳实践 #

🌐 Essential best practices

使用私密通道 #

🌐 Use private channels

在生产应用中总是使用私有通道,以确保正确的安全性和授权:

🌐 Always use private channels for production applications to ensure proper security and authorization:

1
const channel = supabase.channel('room:123:messages', {
2
config: { private: true },
3
})

遵循命名规范 #

🌐 Follow naming conventions

通道主题: 使用模式 scope:id:entity

  • room:123:messages - 123号房的消息
  • game:456:moves - 游戏456的动作
  • user:789:notifications - 用户789的通知

清理订阅 #

🌐 Clean up subscriptions

用完一个通道后一定要退订,以确保释放资源:

🌐 Always unsubscribe when you are done with a channel to ensure you free up resources:

1
// React example
2
import { useEffect } from 'react'
3
4
useEffect(() => {
5
const channel = supabase.channel('room:123:messages')
6
7
return () => {
8
supabase.removeChannel(channel)
9
}
10
}, [])

选择合适的功能 #

🌐 Choose the right feature

什么时候使用广播 #

🌐 When to use Broadcast

  • 实时消息和通知
  • 自定义事件和游戏状态
  • 数据库变更通知(带触发器)
  • 高频更新(例如光标跟踪)
  • 大多数用例

什么时候使用Presence #

🌐 When to use Presence

  • 用户在线/离线状态
  • 活跃用户计数器
  • 尽量少用,因为计算开销大

什么时候使用 Postgres Changes #

🌐 When to use Postgres Changes

  • 快速测试与开发
  • 连接的用户数量少

下一步 #

🌐 Next steps

既然你已经了解了基础知识,就深入了解每个功能吧:

🌐 Now that you understand the basics, dive deeper into each feature:

核心功能 #

🌐 Core features

  • 广播 - 了解发送消息、数据库触发器和 REST API 的使用
  • 在线状态 - 实现用户状态跟踪和在线指示
  • Postgres 变更 - 了解数据库变更监听器(考虑迁移到 Broadcast)

安全与配置 #

🌐 Security & configuration

  • 授权 - 为私密通道设置 RLS 策略
  • 设置 - 配置你的实时实例以获得最佳性能

高级话题 #

🌐 Advanced topics

  • 架构 - 了解实时系统的工作原理
  • 基准测试 - 性能特点与扩展考虑
  • 限制 - 使用限制和最佳实践

集成指南 #

🌐 Integration guides

框架示例 #

🌐 Framework examples

准备好创造一些了不起的东西了吗?从广播指南开始,创建你的第一个实时功能吧!

🌐 Ready to build something amazing? Start with the Broadcast guide to create your first real-time feature!