跳到正文
cccskills
免费在 GitHub 公开

dotnet-health-checks

Configures health checks for database, external services, and custom application checks. Provides liveness and readiness endpoints for container orchestration.

中文简介正在准备中。当前显示原文说明。

集成工具PostgreSQLRedis

实测评分 未实测

查看安装方法

包含的文件(1)

  • SKILL.md8.0 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Health Checks Configuration

Overview

Health checks monitor application dependencies:

  • Liveness - Is the app running?
  • Readiness - Is the app ready to serve traffic?
  • Database checks - PostgreSQL connectivity
  • External service checks - APIs, caches, queues
  • Custom checks - Business logic validation

Quick Reference

Check TypePurpose
AddNpgSqlPostgreSQL database
AddUrlGroupExternal HTTP endpoints
AddRedisRedis cache
AddRabbitMQRabbitMQ message broker
CustomApplication-specific checks

Template: Health Check Registration

// src/{name}.infrastructure/HealthChecks/HealthCheckExtensions.cs
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace {name}.infrastructure.healthchecks;

public static class HealthCheckExtensions
{
    public static IServiceCollection AddHealthChecks(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        services.AddHealthChecks()
            // ═══════════════════════════════════════════════════════════════
            // DATABASE
            // ═══════════════════════════════════════════════════════════════
            .AddNpgSql(
                configuration.GetConnectionString("Database")!,
                name: "postgresql",
                failureStatus: HealthStatus.Unhealthy,
                tags: new[] { "db", "sql", "postgresql", "ready" })

            // ═══════════════════════════════════════════════════════════════
            // EXTERNAL SERVICES
            // ═══════════════════════════════════════════════════════════════
            .AddUrlGroup(
                new Uri(configuration["AuthService:BaseUrl"]!),
                name: "auth-service",
                failureStatus: HealthStatus.Degraded,
                tags: new[] { "external", "auth", "ready" })

            // ═══════════════════════════════════════════════════════════════
            // REDIS (if used)
            // ═══════════════════════════════════════════════════════════════
            // .AddRedis(
            //     configuration.GetConnectionString("Redis")!,
            //     name: "redis",
            //     tags: new[] { "cache", "redis", "ready" })

            // ═══════════════════════════════════════════════════════════════
            // CUSTOM CHECKS
            // ═══════════════════════════════════════════════════════════════
            .AddCheck<DatabaseMigrationHealthCheck>(
                "database-migrations",
                tags: new[] { "db", "migrations", "ready" });

        return services;
    }
}

Template: Custom Health Check

// src/{name}.infrastructure/HealthChecks/DatabaseMigrationHealthCheck.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace {name}.infrastructure.healthchecks;

internal sealed class DatabaseMigrationHealthCheck : IHealthCheck
{
    private readonly ApplicationDbContext _dbContext;

    public DatabaseMigrationHealthCheck(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var pendingMigrations = await _dbContext.Database
                .GetPendingMigrationsAsync(cancellationToken);

            var pending = pendingMigrations.ToList();

            if (pending.Any())
            {
                return HealthCheckResult.Degraded(
                    $"Pending migrations: {string.Join(", ", pending)}",
                    data: new Dictionary<string, object>
                    {
                        { "pending_count", pending.Count },
                        { "migrations", pending }
                    });
            }

            return HealthCheckResult.Healthy("All migrations applied");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy(
                "Failed to check migrations",
                exception: ex);
        }
    }
}

Template: Program.cs Configuration

// src/{name}.api/Program.cs
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;

var app = builder.Build();

// ═══════════════════════════════════════════════════════════════
// LIVENESS: Is the app running?
// ═══════════════════════════════════════════════════════════════
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = _ => false,  // No checks, just confirms app is running
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

// ═══════════════════════════════════════════════════════════════
// READINESS: Is the app ready to serve traffic?
// ═══════════════════════════════════════════════════════════════
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready"),
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

// ═══════════════════════════════════════════════════════════════
// FULL: All health checks
// ═══════════════════════════════════════════════════════════════
app.MapHealthChecks("/health", new HealthCheckOptions
{
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

Kubernetes Configuration

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
        - name: api
          livenessProbe:
            httpGet:
              path: /health/live
              port: 8080
            initialDelaySeconds: 10
            periodSeconds: 30
          readinessProbe:
            httpGet:
              path: /health/ready
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 10

Related Skills

  • dotnet-clean-architecture - Infrastructure layer setup
  • dotnet-jwt-authentication - Auth service health check

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Generates audit trail infrastructure for entities. Implements IAuditable interface, EF Core SaveChanges interceptor, and automatic population of CreatedAt, UpdatedAt, CreatedBy, and UpdatedBy fields.

中文简介正在准备中。当前显示原文说明。

ronnythedev/dotnet-clean-architecture-skills762026年7月14日 更新

Scaffolds a complete .NET solution following Clean Architecture principles with proper layer separation (API, Application, Domain, Infrastructure). Creates project structure, dependency injection setup, and cross-cutting concerns configuration.

中文简介正在准备中。当前显示原文说明。

ronnythedev/dotnet-clean-architecture-skills762026年7月14日 更新

Generates CQRS Commands with Handlers, Validators, and Request DTOs following Clean Architecture patterns. Commands represent actions that modify state and return Result types for proper error handling.

中文简介正在准备中。当前显示原文说明。

ronnythedev/dotnet-clean-architecture-skills762026年7月14日 更新

Generates CQRS Queries with Handlers and Response DTOs for read operations. Uses Dapper for optimized read queries, bypassing the domain model for better performance.

中文简介正在准备中。当前显示原文说明。

ronnythedev/dotnet-clean-architecture-skills762026年7月14日 更新

Generates optimized read queries using Dapper. Includes multi-mapping for joins, pagination, dynamic filtering, CTEs, and best practices for high-performance data access.

中文简介正在准备中。当前显示原文说明。

ronnythedev/dotnet-clean-architecture-skills762026年7月14日 更新

Generates Domain Entities following DDD principles with factory methods, private setters, domain events, and proper encapsulation. Supports aggregate roots, child entities, and value objects.

中文简介正在准备中。当前显示原文说明。

ronnythedev/dotnet-clean-architecture-skills762026年7月14日 更新

查看 ronnythedev 的全部技能

报告此技能的问题