Prometheus 通過consul動態修改Targets接入

Prometheus 通過consul動態修改Targets接入

通常Prometheus 要增加一個target,需要在配置文件中已添加一個job,例如下:

- job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

每次修改需要直接修改服務器上的配置文件,非常麻煩。Prometheus 提供了多種動態服務發現的功能,這裏使用consul來做一個例子。

1.在Prometheus配置文件中配置consul

- job_name: 'consul-prometheus'
    consul_sd_configs:
    #consul 地址
      - server: 'xx.xx.xx.xx:8500'
        services: []
    relabel_configs:
      - source_labels: [__meta_consul_tags]
        regex: .*prometheus-target.*
        action: keep

配置這個之後,Prometheus就會動態發現consul的Service。
這裏使用了 relabel_configs 用法可以參考 https://prometheus.io/docs/prometheus/latest/configuration/configuration/#
我這裏的意思是過濾,只有consul的service的tag爲prometheus-target 的動態發現。
隨後我們只要在consul修改Service即可。

2.consul中註冊服務

consul註冊註冊service 的方式有多種,
如果靜態註冊.
創建文件夾consul.d
添加如下test.json:

{
  "service":{
    "id": "node",
    "name": "prometheus-node",
    "address": "127.0.0.1",
    "port": 9100,
    "tags": ["prometheus-target"],
    "checks": [
        {
            "http": "http://127.0.0.1:9100/metrics",
            "interval": "15s"
        }
    ]
  }
}

在consul啓動命令中,指定配置路徑

-config-dir=consul.d

啓動後查看Prometheus 和consul 界面,可以看到target是否引入。

也可以使用http Api 的方式

curl -X PUT -d '{"service":{"id":"node","name":"prometheus-node","address":"127.0.0.1","port":9100,"tags":["prometheus-target"],"checks":[{"http":"http://127.0.0.1:9100/metrics","interval":"15s"}]}}' http://127.0.0.1:8500/v1/agent/service/register

還可以使用各語音版本的sdk:
https://www.consul.io/api/libraries-and-sdks.html

我這裏使用JAVA 版本的

<dependency>
  <groupId>com.orbitz.consul</groupId>
  <artifactId>consul-client</artifactId>
  <version>1.0.0</version>
</dependency>

使用如下:

public class ConsulTest {
  Consul client;

  /**
   * 初始化.
   */
  @Before
  public void init() {

    client = Consul.builder().withHostAndPort(HostAndPort.fromParts("xx.xx.xx.xx", 8500)).build();
    //  catalogClient = client.catalogClient();
  }

  @Test
  public void queryAll() {
    Map<String, Service> services = client.agentClient().getServices();
    for (Map.Entry<String, Service> entry : services.entrySet()) {
      System.out.println("key:" + entry.getKey());
      System.out.println("value:" + entry.getValue().toString());
    }

  }


  @Test
  public void testDelete() {
    client.agentClient().deregister("etcd");
  }


  @Test
  public void testAdd1() {
    String serviceName = "prometheus-etcd";
    String serviceId = "etcd";
    Registration.RegCheck single = Registration.RegCheck.http("http://127.0.0.1:2379/metrics", 20);
    Registration reg = ImmutableRegistration.builder()
        .check(single)
        .addTags("prometheus-target")
        .address("127.0.0.1")
        .port(2379)
        .name(serviceName)
        .id(serviceId)
        .build();
    client.agentClient().register(reg);
  }



}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章