介绍 Swift Service Lifecycle
我很高兴地宣布 Swift 服务器生态系统的一个新的开源项目:Swift Service Lifecycle。Service Lifecycle 是一个 Swift 包,旨在帮助服务器应用程序(也称为服务)管理其启动和关闭序列。
它是什么?
大多数服务都有启动和关闭工作流程逻辑,这些逻辑通常对故障很敏感且难以正确实现。启动序列包括初始化线程池、运行数据迁移、预热缓存以及在处理流量或接受事件之前的其他形式的状态初始化等操作。关闭序列包括释放持有文件描述符或其他系统资源的资源,如果不正确清除,可能会导致泄漏。
如今,服务器应用程序和框架必须自行找到方法来满足这种需求,这可能容易出错。为了使事情更安全、更容易,Service Lifecycle 以安全、可重用且与框架无关的方式编纂了这种常见需求。它旨在与任何服务器框架集成,或直接集成到服务器应用程序的 main
中。
它是如何工作的?
使用此库的推荐方法是在服务器应用程序的 main
中创建 ServiceLifecycle
实例,并向其注册 LifecycleTasks
。调用 start
函数后,ServiceLifecycle
将按照注册顺序启动这些任务。
默认情况下,ServiceLifecycle
还会注册一个 Signal
处理程序,该处理程序捕获 INT
和 TERM
信号,这些信号是现代部署平台中用于通信关闭请求的典型 Signal
。一旦捕获到 Signal
,关闭序列就会开始,并且 LifecycleTasks
会以与注册顺序相反的顺序关闭。
示例
// Import the package.
import Lifecycle
// Initialize the `Lifecycle` container.
var lifecycle = ServiceLifecycle()
// Register a resource that should be shut down when the application exits.
//
// In this case, we are registering a SwiftNIO `EventLoopGroup`
// and passing its `syncShutdownGracefully` function to be called on shutdown.
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
lifecycle.registerShutdown(
name: "eventLoopGroup",
.sync(eventLoopGroup.syncShutdownGracefully)
)
// Register another resource that should be started when the application starts
// and shut down when the application exits.
//
// In this case, we are registering a contrived `DatabaseMigrator`
// and passing its `migrate` function to be called on startup
// and `shutdown` function to be called on shutdown.
let migrator = DatabaseMigrator(eventLoopGroup: eventLoopGroup)
lifecycle.register(
name: "migrator",
start: .async(migrator.migrate),
shutdown: .async(migrator.shutdown)
)
// Start the application.
//
// Start handlers passed using the `register` function
// will be called in the order they were registered in.
lifecycle.start() { error in
// start completion handler
// if an startup error occurred you can capture it here
if let error = error {
logger.error("failed starting \(self) ☠️: \(error)")
} else {
logger.info("\(self) started successfully 🚀")
}
}
// Wait for the application to exit
//
// This is a blocking operation that typically waits for a `Signal`.
// The `Signal` can be configured at `lifecycle.init`, and defaults to `INT` and `TERM`.
// Shutdown handlers passed using the `register` or `registerShutdown` functions
// will be called in the reverse order they were registered in.
lifecycle.wait()
参与其中
如果您对 Service Lifecycle 感兴趣,请参与进来!
源代码已开源,我们鼓励开源社区贡献代码。如果您有反馈、问题或想讨论该项目,请随时在 Swift 论坛上交流。如果您想报告错误,请使用 GitHub 问题跟踪器。我们期待与您合作,共同推动行业朝着更好、更安全的编程未来发展。