1、导包
<dependency>
<groupId>io.github.hengyunabc</groupId>
artifactId>zabbix-api</artifactId>
<version>0.0.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
artifactId>slf4j-simple</artifactId>
<version>1.7.32</version>
</dependency>
<dependency>
groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
2、登录验证
DefaultZabbixApi zabbixApi = new DefaultZabbixApi("http://ip地址/zabbix/api_jsonrpc.php");
// init方法中创建CloseableHttpClient客户端
zabbixApi.init();
boolean login = zabbixApi.login("Admin", "zabbix");
if(!login){
throw new RuntimeException("zabbix login failed!");
}
3、获取主机
Request request = RequestBuilder.newBuilder().method("host.get")
.paramEntry("output", new String[]{"host", "name", "hostid"})
.build();
JSONObject response = zabbixApi.call(request);
JSONArray result = response.getJSONArray("result");
return result.toJSONString();
method(“host.get”)中填写的是调用的方法名,paramEntry(“output”, “extend”)传递的是接口需要的参数,可同时设置多个paramEntry(“paramName”, “paramValue”)
4、获取监控项
JSONObject json = new JSONObject();
json.put("key_", "Nodes");
Request request = RequestBuilder.newBuilder().method("item.get")
.paramEntry("output",new String[]{"itemid","name","lastvalue","prevvalue"})
.paramEntry("hostids",hostId)
.paramEntry("search",json)
.build();
JSONObject response = zabbixApi.call(request);
JSONArray result = response.getJSONArray("result");
return result.toJSONString();
Finding items by key 根据key “Nodes” 查找"hostId"主机所有"name"含"Nodos"的监控项
5、获取历史监控项
Request request = RequestBuilder.newBuilder().method("history.get")
.paramEntry("output","extend")
.paramEntry("history",3)
.paramEntry("itemids",id)
.paramEntry("time_from",timefrom)
.paramEntry("time_till",timetill)
.paramEntry("sortfield","clock")
.paramEntry("limit",10)
.build();
JSONObject response = zabbixApi.call(request);
JSONArray result = response.getJSONArray("result");
获取某段时间内的某个监控项的10条数据。
其中history为数据类型:
0 - 数字浮点; 1 - 字符串; 2 - 日志; 3 - 无符号数字; 4 - 文本.
timefrom、timetill 为时间戳
limit取10条数据