Zabbix已经搭建完毕,搭建方法见通过docker搭建zabbix5.0
查阅文档:https://www.zabbix.com/documentation/5.0/manual ,发现zabbix对外提供了很多api接口。
于是从某开源网站上面找到了一个jar包见下图
于是开始使用springboot工程去调用api。直接上代码,先是pom文件
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.7.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>io.github.hengyunabc</groupId> <artifactId>zabbix-api</artifactId> <version>0.0.2</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> </dependency> </dependencies>
yml配置
server: port: 9003 logging: level: com.cn.scott: debug zabbix: config: url: http://xxxx:8080/api_jsonrpc.php username: Admin password: zabbix
zabbixConfig用于读取配置信息
@Component @ConfigurationProperties(prefix = "zabbix.config") @Data public class ZabbixConfig { private String url; private String username; private String password; }
工具类用于初始化zabbixApi对象,并且登录获取token值。
@Component @Slf4j public class ZabbixUtil { private volatile ZabbixApi zabbixApi; @Autowired private ZabbixConfig zabbixConfig; public ZabbixApi getZabbixApi() { if (null == zabbixApi) { synchronized (ZabbixUtil.class) { if (null == zabbixApi) { zabbixApi = new DefaultZabbixApi(zabbixConfig.getUrl()); zabbixApi.init(); login(); } } } return zabbixApi; } private void login(){ boolean login = zabbixApi.login(zabbixConfig.getUsername(), zabbixConfig.getPassword()); if(!login){ throw new RuntimeException("zabbix login failed!"); } log.info("zabbix login success!"); } }
最后业务类负责调用接口,写了两个demo,其他大同小异
@Service public class ZabbixService extends AbstractZabbixService{ @Autowired private ZabbixUtil zabbixUtil; //获取主机列表 public String getHostList() throws Exception { ZabbixApi zabbixApi = zabbixUtil.getZabbixApi(); Request request = RequestBuilder.newBuilder().method("host.get") .paramEntry("output", new String[]{"host", "name", "description", "hostid"}) .paramEntry("selectGroups", "extend") .build(); JSONObject response = zabbixRequest(zabbixApi,request); zabbixError(response); JSONArray result = response.getJSONArray("result"); return result.toJSONString(); } //获取监控项 public String getMonitorItems(String hostId) throws Exception { ZabbixApi zabbixApi = zabbixUtil.getZabbixApi(); Request request = RequestBuilder.newBuilder().method("item.get") .paramEntry("output","extend").paramEntry("hostids",hostId).build(); JSONObject response = zabbixRequest(zabbixApi,request); zabbixError(response); JSONArray result = response.getJSONArray("result"); return result.toJSONString(); } }
如需查看具体代码,请移步:https://gitee.com/ErGouGeSiBaKe/zabbixapi