簡體   English   中英

如何在Java代碼中獲取Docker統計信息的詳細信息?

[英]How to get docker stats detail in java code?

我嘗試在我的Java代碼上獲取docker容器的詳細信息,並成功獲取它。 但是我需要獲取Docker容器的CPU和內存使用率。 在終端本身中,我們可以使用docker stats檢查狀態。 但是我的問題是如何在Java代碼中獲取Docker容器的統計信息?

Docker CLI調用Docker API

您也可以使用GitHub上的Java API客戶端。

回答有點晚,但可能會對某人有所幫助。

考慮到您的主機上正在運行Docker引擎,您可以對Docker API端點進行RESTful調用以獲取各種響應,請參見Docker API端點列表。

現在,要獲取特定容器的內存和CPU使用率(以及更多),您可以調用http://localhost:2375/containers/some-containerId/stats?stream=0 API端點。

在瀏覽器上訪問此鏈接並查看響應,對於Java,請參見以下內容-

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestTemplate;

@RestController
public class DockerController {
    @GetMapping("/getStats/{containerId}")
    public String getStats(@PathVariable String containerId){
        String statistics = null;
        RestTemplate restTemplate =  new RestTemplate();
        statistics = restTemplate.getForObject("http://localhost:2375/containers/"+containerId+"/stats?stream=0", String.class);
        if(statistics != null){
            System.out.println("Container statistics - \n" + statistics);
        }
        return statistics;
    }
}

注意stream=false查詢參數將提取一次統計信息,然后斷開連接。 默認值為true 如果選擇stream=true則將獲得連續的統計信息流。

在這里,我以String獲取統計信息,也可以以HashMap獲取統計信息。

如果您在瀏覽器http://localhost:2375/containers/some-containerId/stats?stream=0上觸發此鏈接,則上述方法的輸出將類似於您的輸出。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM