如何与运行在Linux上的.NET Core后台服务进行交互?
实现Linux下.NET Core可交互后台服务的步骤
一、代码开发调整
你需要先补全应用的命令行解析逻辑,支持接收调用时传入的子命令和参数,推荐用官方的System.CommandLine库实现,不需要手动写参数解析逻辑:
- 首先调整你的业务代码,补全类定义:
namespace MyApp { public class AppService { public void Echo(string input) { Console.WriteLine(input); } } }
- 然后在Program.cs中添加命令行解析逻辑:
using System.CommandLine; using MyApp; // 定义Echo子命令 var echoCommand = new Command("Echo", "输出输入的内容") { new Argument<string>("input", "需要输出的文本内容") }; // 绑定Echo命令的执行逻辑 echoCommand.SetHandler((string input) => { new AppService().Echo(input); }, echoCommand.Arguments.OfType<Argument<string>>().First()); // 定义根命令 var rootCommand = new RootCommand("MyApp 后台服务工具"); rootCommand.AddCommand(echoCommand); // 如果需要支持后台常驻模式,再加一个run子命令 var runCommand = new Command("run", "启动后台常驻服务"); runCommand.SetHandler(() => { // 这里写后台服务的常驻逻辑,比如监听Unix套接字接收命令、定时任务等 Console.WriteLine("MyApp后台服务已启动"); while(true) { Thread.Sleep(1000); } }); rootCommand.AddCommand(runCommand); return await rootCommand.InvokeAsync(args);
如果你需要实现给常驻后台的服务发送命令执行,可以在后台服务里监听Unix Domain Socket,前台执行MyApp Echo xxx时把参数通过套接字发给后台服务,拿到结果后输出即可,不需要每次调用都启动新进程。
二、Linux环境配置
- 先在目标Linux机器上安装对应版本的.NET Core Runtime,安装完成后执行
dotnet --version验证是否安装成功。 - 发布你的应用:在开发机执行命令
dotnet publish -c Release -r linux-x64 --self-contained false,如果不想在Linux上装.NET环境,可以把--self-contained改成true,打包出来的文件会包含运行时,体积更大但不需要额外装依赖。 - 把发布后的所有文件上传到Linux的
/opt/MyApp目录下,给主程序加执行权限:chmod +x /opt/MyApp/MyApp - 配置全局命令软链接,这样任意目录下都可以直接调用MyApp命令:
ln -s /opt/MyApp/MyApp /usr/local/bin/MyApp,配置完成后执行MyApp Echo 'hello world'就可以直接看到输出结果。
三、systemd服务配置
如果需要把应用作为常驻后台服务运行,按照以下步骤配置systemd:
- 新建服务配置文件
/etc/systemd/system/MyApp.service,内容如下:
[Unit] Description=MyApp .NET 后台服务 After=network.target [Service] Type=simple ExecStart=/opt/MyApp/MyApp run WorkingDirectory=/opt/MyApp User=root Restart=always RestartSec=10 SyslogIdentifier=MyApp [Install] WantedBy=multi-user.target
- 执行
systemctl daemon-reload让配置生效 - 常用systemd交互命令:
- 启动服务:
systemctl start MyApp - 停止服务:
systemctl stop MyApp - 查看服务运行状态:
systemctl status MyApp - 设置开机自启:
systemctl enable MyApp - 查看服务实时日志:
journalctl -u MyApp -f
- 启动服务:
内容的提问来源于stack exchange,提问作者TTomer
相关产品推荐
相关产品推荐

