640?wx_fmt=jpeg

给 asp.net core 写一个简单的健康检查

Intro

健康检查可以帮助我们知道应用的当前状态是不是处于良好状态,现在无论是 docker 还是 k8s 还是现在大多数的服务注册发现大多都提供了健康检查机制来检测应用的健康状态,如果应用本身就提供一个健康检查的机制会更友好,更能真实的反映出应用的健康状态。

我们的开发环境虚拟机配置有点低,所以有时候虚拟机会卡死。。导致接口无响应,有时可能有些服务启动有问题会挂掉,所以需要一个简单的健康检查机制去检查应用的健康状态来第一时间知道应用出现异常。

健康检查扩展实现

实现源码

 
 
  1. public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder applicationBuilder)

  2. {

  3. return UseHealthCheck(applicationBuilder, new PathString("/api/health"));

  4. }


  5. public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder applicationBuilder, string path)

  6. {

  7. return UseHealthCheck(applicationBuilder, new PathString(path));

  8. }


  9. public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder applicationBuilder, PathString path)

  10. {

  11. applicationBuilder.Map(path, builder => builder.Use(

  12. (context, next) =>

  13. {

  14. context.Response.StatusCode = 200;

  15. return context.Response.WriteAsync("healthy");

  16. }));

  17. return applicationBuilder;

  18. }


  19. public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder applicationBuilder, string path, Func<IServiceProvider, bool> checkFunc)

  20. {

  21. return UseHealthCheck(applicationBuilder, new PathString(path), serviceProvider => Task.FromResult(checkFunc(serviceProvider)));

  22. }


  23. public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder applicationBuilder, string path,

  24. Func<IServiceProvider, Task<bool>> checkFunc)

  25. {

  26. return UseHealthCheck(applicationBuilder, new PathString(path), checkFunc);

  27. }


  28. public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder applicationBuilder, PathString path, Func<IServiceProvider, bool> checkFunc)

  29. {

  30. if (checkFunc == null)

  31. {

  32. checkFunc = serviceProvider => true;

  33. }

  34. return UseHealthCheck(applicationBuilder, path, serviceProvider => Task.FromResult(checkFunc(serviceProvider)));

  35. }


  36. public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder applicationBuilder, PathString path, Func<IServiceProvider, Task<bool>> checkFunc)

  37. {

  38. if (checkFunc == null)

  39. {

  40. checkFunc = serviceProvider => Task.FromResult(true);

  41. }

  42. applicationBuilder.Map(path, builder => builder.Use(

  43. async (context, next) =>

  44. {

  45. try

  46. {

  47. var healthy = await checkFunc.Invoke(context.RequestServices);

  48. if (healthy)

  49. {

  50. context.Response.StatusCode = StatusCodes.Status200OK;

  51. await context.Response.WriteAsync("healthy");

  52. }

  53. else

  54. {

  55. context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;

  56. await context.Response.WriteAsync("unhealthy");

  57. }

  58. }

  59. catch (Exception ex)

  60. {

  61. context.RequestServices.GetService<ILoggerFactory>().CreateLogger("HealthCheck").Error(ex);

  62. context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;

  63. await context.Response.WriteAsync("unhealthy");

  64. }

  65. }));

  66. return applicationBuilder;

  67. }

配置健康检查

Startup 里配置健康检查,示例代码

 
 
  1. app.UseHealthCheck(); // 最基本的健康检查, 默认检查路径为 ""/api/health",直接返回 healthy

  2. app.UseHealthCheck("/heath"); // 配置健康检查的路径为 "/health",直接返回 healthy


  3. app.UseHealthCheck("/health", serviceProvider =>

  4. {

  5. // 检查数据连接是否正常,这里只是一个示例,可以根据需要自定义自己的实现

  6. var configuration = serviceProvider.GetService<IConfiguration>();

  7. var connString = configuration.GetConnectionString("DefaultConnection");

  8. try

  9. {

  10. using (var conn = new SqlConnection(connString))

  11. {

  12. conn.EnsureOpen();

  13. }

  14. return true;

  15. }

  16. catch (Exception)

  17. {

  18. return false;

  19. }

  20. });

实际效果

直接启动访问 "/health"

640?wx_fmt=png

数据库连接改为一个错误的连接,修改数据库名称为一个不存在的数据库

640?wx_fmt=png

End

这个实现比较简单,只是实现一个比较简单的检查,最初的想法比较简单只是看某个应用是否正常工作,具体的检查逻辑可以自定义。官方的 HealthChecks 的实现稍为复杂,下次单独写一篇文章介绍。


Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐