接觸小米這款運維軟體Open-Falcon一周了,最近想用java來嘗試push資料。下面是我的測試代碼:
private static void Test(){
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://127.0.0.1:1988/v1/push");
JSONObject js = new JSONObject();
js.put("endpoint","test");
js.put("metric","test-metric");
js.put("timestamp",System.currentTimeMillis());
js.put("step",60);
js.put("value", 100);
js.put("counterType", "GAUGE");
js.put("tags","mark=test");
StringEntity s = new StringEntity("["+js.toString()+"]"); //一開始沒加[],一直報錯誤400
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == 200){
HttpEntity entity = res.getEntity();
System.out.println(EntityUtils.toString(entity));
}
}
catch(Exception e){
System.out.println(e);
}
}
上面需要用到json的相關包和httpclient、httpcore包。
根據需要修改代碼後,打包成可運作的jar包,部署到對應的linux伺服器上,配置為crontab程序,即可實作定時push資料到agent上面。