.NET Core 中的跨平台后台服务(想想 windows service/unix 守护进程)?
Cross-platform background service in .NET Core (think windows service/unix daemon)?
所以我有一个由 API 和 Windows 服务(由 Topshelf 包装)组成的应用程序,该服务使用 RabbitMQ 持续侦听事件并按需处理数据。
为了教育和娱乐,我正在尝试将其重写为等效设置,该设置将 运行 在 .NET Core 和 unix 上(例如在 AWS 上的 docker 容器中)
如果我愿意,使用 .NET Core 实现与 windows 服务等同的东西(永远-运行ning 后台进程)的最佳方法是什么保持跨平台?
Windows 服务本身是一个控制台应用程序,它符合 Windows 服务控制管理器的接口规则和协议。您可以使用 .net 核心控制台应用程序在两个平台上实现相同的目的,因为 host.It 需要做一些额外的配置才能使其表现得更像一个真正的服务/守护进程。
Linux
例如对于 Linux,您可以使用 SystemD。
您需要先创建一个类似这样的 SystemD 配置文件:
[Unit]
Description=daemon service
After=network.target
[Service]
ExecStart=/usr/bin/dotnet $(pwd)/bin/daemonsrv.dll 10000
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
然后配置 SystemD 使其知道您的服务配置
# Copy service file to a System location
sudo cp daemonsrv.service /lib/systemd/system
# Reload SystemD and enable the service, so it will restart on reboots
sudo systemctl daemon-reload
sudo systemctl enable daemonsrv
# Start service
sudo systemctl start daemonsrv
# View service status
systemctl status daemonsrv
Windows
对于 windows 你应该做大部分相同的事情,但使用不同的工具集。您将不得不使用第三方服务管理器来避免紧密的 windows 绑定。
例如。你可以使用 NSSM. And here is the nice article with examples about it - .Net Core console application as a Windows Service。
顺便说一句,在 Windows 的情况下,您仍然可以使用正常的 windows 服务设置作为主机。并为您的 Unix 环境编写另一个主机(控制台应用程序主机)。他们都可以共享业务逻辑,只是他们对系统事件的反应方式不同。
希望对您有所帮助。
查看 Worker 服务(.NET Core 3.x):
您可以从新的 Visual Studio 2019 Worker Service 项目模板或使用 .NET CLI 创建一个:
dotnet new worker
所以我有一个由 API 和 Windows 服务(由 Topshelf 包装)组成的应用程序,该服务使用 RabbitMQ 持续侦听事件并按需处理数据。
为了教育和娱乐,我正在尝试将其重写为等效设置,该设置将 运行 在 .NET Core 和 unix 上(例如在 AWS 上的 docker 容器中)
如果我愿意,使用 .NET Core 实现与 windows 服务等同的东西(永远-运行ning 后台进程)的最佳方法是什么保持跨平台?
Windows 服务本身是一个控制台应用程序,它符合 Windows 服务控制管理器的接口规则和协议。您可以使用 .net 核心控制台应用程序在两个平台上实现相同的目的,因为 host.It 需要做一些额外的配置才能使其表现得更像一个真正的服务/守护进程。
Linux
例如对于 Linux,您可以使用 SystemD。 您需要先创建一个类似这样的 SystemD 配置文件:
[Unit]
Description=daemon service
After=network.target
[Service]
ExecStart=/usr/bin/dotnet $(pwd)/bin/daemonsrv.dll 10000
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
然后配置 SystemD 使其知道您的服务配置
# Copy service file to a System location
sudo cp daemonsrv.service /lib/systemd/system
# Reload SystemD and enable the service, so it will restart on reboots
sudo systemctl daemon-reload
sudo systemctl enable daemonsrv
# Start service
sudo systemctl start daemonsrv
# View service status
systemctl status daemonsrv
Windows
对于 windows 你应该做大部分相同的事情,但使用不同的工具集。您将不得不使用第三方服务管理器来避免紧密的 windows 绑定。 例如。你可以使用 NSSM. And here is the nice article with examples about it - .Net Core console application as a Windows Service。
顺便说一句,在 Windows 的情况下,您仍然可以使用正常的 windows 服务设置作为主机。并为您的 Unix 环境编写另一个主机(控制台应用程序主机)。他们都可以共享业务逻辑,只是他们对系统事件的反应方式不同。
希望对您有所帮助。
查看 Worker 服务(.NET Core 3.x):
您可以从新的 Visual Studio 2019 Worker Service 项目模板或使用 .NET CLI 创建一个:
dotnet new worker