5.9.3. 服务监控器


ServiceMonitor 是 Prometheus Operator 提供的自定义资源,用于发现 Service 对象中的 Endpoints,配置 Prometheus 以监控这些 pod。

在使用 Operator SDK 生成的基于 Go 的 Operator 中,GenerateServiceMonitor() 帮助函数可以获取 Service 对象并基于该对象生成 ServiceMonitor 对象。

5.9.3.1. 创建服务监控器

Operator 作者可使用 metrics.CreateServiceMonitor() 帮助函数来添加已创建监控服务的服务目标发现,该函数接受新创建的 Service。

先决条件

  • 使用 Operator SDK 生成基于 Go 的 Operator
  • 基于 Kubernetes 的集群已部署 Prometheus Operator

流程

  • metrics.CreateServiceMonitor() 帮助函数添加至您的 Operator 代码中:

    import(
        "k8s.io/api/core/v1"
        "github.com/operator-framework/operator-sdk/pkg/metrics"
        "machine.openshift.io/controller-runtime/pkg/client/config"
    )
    func main() {
    
        ...
        // Populate below with the Service(s) for which you want to create ServiceMonitors.
        services := []*v1.Service{}
        // Create one ServiceMonitor per application per namespace.
        // Change the below value to name of the Namespace you want the ServiceMonitor to be created in.
        ns := "default"
        // restConfig is used for talking to the Kubernetes apiserver
        restConfig := config.GetConfig()
    
        // Pass the Service(s) to the helper function, which in turn returns the array of ServiceMonitor objects.
        serviceMonitors, err := metrics.CreateServiceMonitors(restConfig, ns, services)
        if err != nil {
            // Handle errors here.
        }
        ...
    }
    Copy to Clipboard Toggle word wrap
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2026 Red Hat