Asp.NetCore远程自启动、重启、关闭实现
一、背景
NetCore作为微服务可以注册到服务中心,服务中心可以远程启动、重启、关闭该微服务
二、实现
1、创建一个NetCore 2.0 WebApi项目
2、创建一个进程去管理NetCore程序进程
public class ApplicationManager
{ private static ApplicationManager _appManager;
private IWebHost _web;
private CancellationTokenSource _tokenSource;
private bool _running;
private bool _restart; public bool Restarting => _restart; public ApplicationManager()
{
_running = false;
_restart = false; } public static ApplicationManager Load()
{
if (_appManager == null)
_appManager = new ApplicationManager(); return _appManager;
} public void Start()
{
if (_running)
return; if (_tokenSource != null && _tokenSource.IsCancellationRequested)
return; _tokenSource = new CancellationTokenSource();
_tokenSource.Token.ThrowIfCancellationRequested();
_running = true; _web = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build(); _web.Run(_tokenSource.Token);
} public void Stop()
{
if (!_running)
return; _tokenSource.Cancel();
_running = false;
} public void Restart()
{
Stop(); _restart = true;
_tokenSource = null;
}
}
3、把ApplicationManager加入到Main中
public static void Main(string[] args)
{
try
{
var appManager = ApplicationManager.Load(); do
{
appManager.Start();
} while (appManager.Restarting); }
catch (Exception ex)
{ }
}
4、在程序的ValuesController中实现重启、关闭的Api
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; namespace NetCoreWebApiDemo.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
private ApplicationManager appManager = ApplicationManager.Load(); // GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} // GET api/values/5
[HttpGet("{cmd}")]
public string Get(string cmd)
{
switch (cmd)
{
case "restart": appManager.Restart(); break;
case "stop": appManager.Stop(); break;
case "start": appManager.Start(); break;
}
return cmd;
} // POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
} // PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
} // DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
6、给程序启动和停止加入日志标签
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace NetCoreWebApiDemo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseMvc(); lifetime.ApplicationStarted.Register(OnStart);//1:应用启动时加载配置,2:应用启动后注册服务中心
lifetime.ApplicationStopped.Register(UnRegService);//应用停止后从服务中心注销
}
private void OnStart()
{
LoadAppConfig();
RegService();
}
private void LoadAppConfig()
{
//加载应用配置
Console.WriteLine("ApplicationStarted:LoadAppConfig");
} private void RegService()
{
//先判断是否已经注册过了
//this code is called when the application stops
Console.WriteLine("ApplicationStarted:RegService");
}
private void UnRegService()
{
//this code is called when the application stops
Console.WriteLine("ApplicationStopped:UnRegService");
}
}
}
5、在程序根目录运行dotnet run

访问:http://localhost:51062/api/values,显示:["Value1","Value2"]

访问:http://localhost:51062/api/values/restart:显示restart,再访问http://localhost:51062/api/values正常返回["Value1","Value2"]


访问:http://localhost:51062/api/values/stop,显示:stop,再访问http://localhost:51062/api/values就是404了



stop后由于netcore进程已经被关闭,没有了http监听,通过url方式是无法重新启动了,这里可以借助类似supervisor的工具来停止进程,启动进程。
三、源码地址
https://github.com/andrewfry/AspNetCore-App-Restart
四、其它实现
1、除了上面,还可以通过中间件的形式,实现远程关闭
新增一个中间件的类:
public class RemoteStopMiddleware
{
private RequestDelegate _next;
private const string RequestHeader = "Stop-Application";
private const string ResponseHeader = "Application-Stopped"; public RemoteStopMiddleware(RequestDelegate next)
{
_next = next;
} public async Task Invoke(HttpContext context, IApplicationLifetime lifetime)
{
if (context.Request.Method == "HEAD" && context.Request.Headers[RequestHeader].FirstOrDefault() == "Yes")
{
context.Response.Headers.Add(ResponseHeader, "Yes");
lifetime.StopApplication();
}
else if (context.Request.Method == "HEAD" && context.Request.Headers[RequestHeader].FirstOrDefault() == "No")
{
context.Response.Headers.Add(ResponseHeader, "No");
// See you on the next request.
//Program.Shutdown();
}
else
{
await _next(context);
}
}
}
2、注册中间件
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseMvc();
app.UseMiddleware<RemoteStopMiddleware>();
lifetime.ApplicationStarted.Register(OnStart);//1:应用启动时加载配置,2:应用启动后注册服务中心
lifetime.ApplicationStopped.Register(UnRegService);//应用停止后从服务中心注销
}
3、运行程序,用postman发起一个head请求,请求头中加
{
Stop-Application:Yes
}
详细说明可参考:https://www.cnblogs.com/artech/p/application-life-time.html
Asp.NetCore远程自启动、重启、关闭实现的更多相关文章
- powershell 远程重启/关闭服务器
powershell 远程重启/关闭服务器 #启动winrm PS C:\Windows\system32> winrm quickconfig -q #设置信任主机 PS C:\Windows ...
- Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践(一)
环境 本地 win7 服务器:Virtual Box 上的Centos ssh工具: Xshell 文件传输: xftp 1.在本地创建asp.net core应用发布 1.1 使用Vs2017 新建 ...
- Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践
原文:Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践 环境 本地 win7 服务器:Virtual Box 上的Centos ssh工具: Xshell 文件传输 ...
- oracle 配置 自启动 和 关闭
今天在看oracle自启动脚本,突然有点时间,总结一下!!! 第一次写博客,大家随便看看就好,有错误麻烦提醒下,不喜欢别喷,主要是锻炼自己,形成写博客的好习惯. 刚毕业,现在还没转正,在干运维和自学d ...
- Asp.NetCore轻松学-使用Supervisor进行托管部署
前言 上一篇文章 Asp.NetCore轻松学-部署到 Linux 进行托管 介绍了如何在 Centos 上部署自托管的 .NET Core 应用程序,接下来的内容就是介绍如何使用第三方任务管理程序来 ...
- Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践(二)
Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践(一) 接上一篇 3. Nginx配置反向代理 3.1 cnetos 安装nginx 首先,我们需要在服务器上安装N ...
- 使用PowerShell自动部署ASP.NetCore程序到IIS
Windows PowerShell 是一种命令行外壳程序和脚本环境,使命令行用户和脚本编写者可以利用 .NET Framework的强大功能.有关于更多PowerShell的信息,可参阅百度词条 接 ...
- Asp.Net 远程连接Oracle数据库
Asp.Net 远程连接Oracle数据库 首先从微软停止.Net FrameWork支持Oracle数据库的研发,转为第三方提供说起,微软是很有实力的公司,他在桌面领域令其他对手望其项背,产品战线也 ...
- ASP.NETCore使用AutoFac依赖注入
原文:ASP.NETCore使用AutoFac依赖注入 实现代码 1.新建接口类:IRepository.cs,规范各个操作类的都有那些方法,方便管理. using System; using Sys ...
随机推荐
- LeetCode OJ:Search Insert Position(查找插入位置)
Given a sorted array and a target value, return the index if the target is found. If not, return the ...
- 【html】html笔记综合
基本标签与属性 <html>全部 <body>主体 <h1>标题 <p>段落 <br>空行,一般都会额外添加,并不总是需要自己添加,可以在& ...
- Java加载jar文件并调用jar文件当中有参数和返回值的方法
在工作当中经常遇到反编译后的jar文件,并要传入参数了解其中的某些方法的输出,想到Java里面的反射可以实现加载jar文件并调用其中的方法来达到自己的目的.就写了个Demo代码. 以下的类可以编译生成 ...
- spring 和springmvc 在 web.xml中的配置
(1)问题:如何在Web项目中配置Spring的IoC容器? 答:如果需要在Web项目中使用Spring的IoC容器,可以在Web项目配置文件web.xml中做出如下配置: <!-- Sprin ...
- 第1章 Flex介绍
* Flex Flex 是一个高效.免费的开源框架,可用于构建具有表现力的 Web应用程序,这些应用程序利用Adobe Flash Player和Adobe AIR, 可以实现跨浏览器.桌面和操作系统 ...
- 你必须知道的495个C语言问题,学习体会二
这是本主题的第二篇文章,主要就结构体,枚举.联合体做一些解释 1.结构体 现代C语言编程 结构化的基石,diy时代的最好代言人,是面向对象编程中类的老祖宗. 我们很容易定义一个结构体,比如学生: st ...
- BZOJ - 2141 排队 (动态逆序对,区间线段树套权值线段树)
题目链接 交换两个数的位置,只有位于两个数之间的部分会受到影响,因此只需要考虑两个数之间有多少数对a[l]和a[r]产生的贡献发生了变化即可. 感觉像是个带修改的二维偏序问题.(修改点$(x,y)$的 ...
- postman安装Postman Interceptor 插件
做后端开发避免不了进行接口调试,但是一般的项目都是前后端分离的,如果把前端代码下到本地,较为费事,这个时候就需要一个可以进行接口调试的工具.Postman就是一个不错的选择. Postman是什么? ...
- Robot Framework接口测试(1)
RF是做接口测试的一个非常方便的工具,我们只需要写好发送报文的脚本,就可以灵活的对接口进行测试. 做接口测试我们需要做如下工作: 1.拼接发送的报文 2.发送请求的方法 3.对结果进行判断 我们先按步 ...
- WCF日志跟踪SvcTraceViewer.exe
参考: https://msdn.microsoft.com/zh-cn/library/ms732023.aspx https://msdn.microsoft.com/zh-cn/library/ ...