mcpField
S
serverpod-sessions

serverpod-sessions

github.com/serverpod开发3.3k44 次安装1 天前更新
代码仓库

关于 serverpod-sessions

用于说明 Serverpod 会话生命周期、会话类型及安全手动管理方式的技能,涵盖清理、错误日志,以及避免在请求结束后继续使用会话。

主要功能

  1. 01会话类型与生命周期
  2. 02自动管理会话生命周期
  3. 03使用 withSession 管理手动会话
  4. 04清理回调
  5. 05避免使用已关闭会话的指南

适用场景

  1. 01为任务选择会话类型
  2. 02管理内部工作所需会话
  3. 03避免请求返回后继续使用会话

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/serverpod/serverpod --skill serverpod-sessions

安装后在 Claude Code 中输入/serverpod-sessions确认已加载。

详细介绍

Serverpod 会话

Session 提供对数据库、缓存、存储、消息、密码和日志的访问。框架会自动创建并关闭 Session;只有 InternalSession 需要手动管理。不要将请求 Session 存起来,用于超出请求、流或 future 调用生命周期的工作。

Session 类型

类型创建用途生命周期
MethodCallSessionEndpoint 方法单次请求
WebCallSessionWeb 服务路由单次请求
MethodStreamSessionStream 方法Stream 持续期间
FutureCallSessionFuture 调用任务执行期间
InternalSession手动创建直到关闭

手动管理 Session(InternalSession)

优先使用 withSession,它会为你关闭 Session;如果回调抛出异常,还会将错误和堆栈跟踪附加到日志中:

await Serverpod.instance.withSession((session) async {
  await doWork(session);
});

如果无法通过回调表示生命周期,请手动创建 Session,并始终在 finally 块中将其关闭:

var session = await Serverpod.instance.createSession();
try {
  await doWork(session);
} finally {
  await session.close();
}

未关闭的 Session 会造成内存泄漏,且日志永远不会持久化。使用已关闭的 Session 会抛出 StateError。

清理回调

session.addWillCloseListener((session) async {
  // Runs just before session closes (all session types)
});

常见陷阱:方法返回后继续使用 Session

Endpoint 返回时,Session 会关闭。不要将其捕获以供后续使用:

// BAD — session already closed when callback runs
Timer(Duration(seconds: 5), () => user.updateLastSeen(session));

修复方法: 使用 future call(session.serverpod.futureCalls.callWithDelay(...)),或在回调中通过 Serverpod.instance.withSession(...) 打开新的 Session。

评论

支持 Markdown