spring cloud圖形化dashboard是如何實現指標的收集展示的
1、dashboard圖形化界面入口
http://localhost:10000/hystrix.stream
說明:端口是由配置文件server.port=10000來指定的,可以修改。
打開后可以看到如下的界面
輸入需要監控的集群,然后點擊Monitor Stream按鈕,進行集群監控
這邊假設輸入
http://localhost:10000/turbine.stream?cluster=default
可以看到下面的界面
注:如果看到的是空白頁面,需要訪問一下開啟了@HystrixCommand
注解的rest方法,本文中有兩個方法,hello、hellosleep方法。
@GetMapping("/hello")
@HystrixCommand(fallbackMethod = "helloFallback")
public String hello() {
return "provide hello world";
}
@GetMapping("/hellosleep")
@HystrixCommand(fallbackMethod = "helloexFallback")
public String hellosleep() throws InterruptedException {
int i = 2000;
TimeUnit.MILLISECONDS.sleep(i);
return "provide hellosleep world!";
}
2、dashboard是如何實現監控數據的獲取的。
我們通過瀏覽器工具打開網絡監控,或者使用F12快捷鍵查看監控的url。
如下:
url:
http://localhost:10000/proxy.stream?origin=http%3A%2F%2Flocalhost%3A10000%2Fturbine.stream%3Fcluster%3Ddefault
我們看到,它是通過proxy.stream來獲取數據,有一個origin
參數,就是前面我們輸入的想要監控的那個url地址,即【http://localhost:10000/turbine.stream?cluster=default
】。proxy.stream
其實對應的是一個servlet
。
查看源碼:
HystrixDashboardConfiguration
可以看到它有一個內部類ProxyStreamServlet
就是用來處理這個url的。
關鍵源碼如下:
這個servlet其實就是通過origin來獲取數據,如果我們直接訪問origin所對應的地址,可以看到如下的數據,像流一樣源源不斷的打印出來。
圖形化的界面其實就是從這個servlet獲取數據,並展示的
3、servlet怎么把流數據返回
httpget = new HttpGet(proxyUrl);
HttpClient client = ProxyConnectionManager.httpClient;
HttpResponse httpResponse = client.execute(httpget);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
is = httpResponse.getEntity().getContent();
//省略代碼...
OutputStream os = response.getOutputStream();
int b = -1;
while ((b = is.read()) != -1) {
try {
os.write(b);
if (b == 10 /** flush buffer on line feed */
) {
os.flush();
}
}
catch (Exception ex) {
//省略代碼...
}
}
}
servlet其實就是通過url去獲取響應結果,然后不斷的輸出到前台頁面。
4、前台界面怎么展示不斷響應回來的流數據呢
這邊主要用到了HTML5的一個對象EventSource
,可以獲取到這個數據。
注意: EventSource
不支持IE瀏覽器,這邊使用谷歌瀏覽器
我們還是通過瀏覽器工具,查看圖形化界面的使用到js腳本。
如下:
EventSource
對象可以對url進行監聽,並注冊響應函數。這里不進行展開,有興趣的同學可以詳細的閱讀里面的腳本。
5、總結
turbine收集的數據是一種json格式的數據,而且像流一樣不斷輸出。所以我們需要借助圖形化工具來展示。而圖形化工具的數據訂閱我們通過上面的分析已經知道,其實他就是通過servlet來訪問turbine的鏈接來獲取數據並展現的。