Java使用zabbix示例


1、创建类ZabbixRequest

public class ZabbixRequest {
	String jsonrpc = "2.0";

	String method;

	String auth;

	Integer id;

	

	public String getJsonrpc() {
		return jsonrpc;
	}

	public void setJsonrpc(String jsonrpc) {
		this.jsonrpc = jsonrpc;
	}


	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public String getAuth() {
		return auth;
	}

	public void setAuth(String auth) {
		this.auth = auth;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

}

2、创建类ZabbixRequestObject

public class ZabbixRequestObject extends ZabbixRequest {
	
	private Object params;

	public Object getParams() {
		return params;
	}

	public void setParams(Object params) {
		this.params = params;
	}
	
}

3、创建类ZabbixRequestParams

import java.util.HashMap;
import java.util.Map;

public class ZabbixRequestParams extends ZabbixRequest {
	
	private Map params = new HashMap();

	public Map getParams() {
		return params;
	}

	public void setParams(Map params) {
		this.params = params;
	}
	
	
	public void putParam(String key, Object value) {
		params.put(key, value);
	}

	public Object removeParam(String key) {
		return params.remove(key);
	}
}

4、创建类ZabbixRequestBuilder

import java.util.concurrent.atomic.AtomicInteger;


public class ZabbixRequestBuilder {
	 private static final AtomicInteger nextId = new AtomicInteger(1);

	 	ZabbixRequest request ;
		
	 	ZabbixRequestObject obj= new ZabbixRequestObject();
	 	ZabbixRequestParams param = new ZabbixRequestParams();
	 	
		private  ZabbixRequestBuilder(String str){
			if("obj".equals(str)){
				this.request= obj;
			}else{
				this.request = param;
			}
		}
		
	
	 	
		static public ZabbixRequestBuilder newBuilder(String str){
			return new ZabbixRequestBuilder(str);
		}
		
		static public ZabbixRequestBuilder newBuilder(){
			return new ZabbixRequestBuilder("param");
		}
		
		public ZabbixRequest build(){
			if(request.getId() == null){
				request.setId(nextId.getAndIncrement());
			}
			return request;
		}
		
		public ZabbixRequestBuilder version(String version){
			request.setJsonrpc(version);
			return this;
		}
		
		public ZabbixRequestBuilder paramEntry(String key, Object value){
			if(request instanceof ZabbixRequestParams){
				((ZabbixRequestParams) request).putParam(key, value);
			}
			return this;
		}
		
		/**
		 * Do not necessary to call this method.If don not set id, ZabbixApi will auto set request auth.. 
		 * @param auth
		 * @return
		 */
		public ZabbixRequestBuilder auth(String auth){
			request.setAuth(auth);
			return this;
		}
		
		public ZabbixRequestBuilder method(String method){
			request.setMethod(method);
			return this;
		}
		
		/**
		 * Do not necessary to call this method.If don not set id, RequestBuilder will auto generate.
		 * @param id
		 * @return
		 */
		public ZabbixRequestBuilder id(Integer id){
			request.setId(id);
			return this;
		}
		
		
		public ZabbixRequestBuilder object(Object obj){
			if(request instanceof ZabbixRequestObject){
				((ZabbixRequestObject)request).setParams(obj);
			}
			
			return this;
			
		}
}

5、公用方法


public  class  ZabbixShare {
	private static final Logger logger = LoggerFactory.getLogger(ZabbixShare.class);

	@Autowired
    Environment env;

	private String auth;
    
	
	public String getAuth() {
		return auth;
	}

	public void setAuth(String auth) {
		this.auth = auth;
	}

	public boolean login() throws URISyntaxException {
		 String uname =env.getProperty("ZABBIX_UNAME");
		 String upwd =env.getProperty("ZABBIX_UPWD") ;
		 
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder().paramEntry("user",uname )
				.paramEntry("password",upwd ).method("user.login").build();
		JSONObject response = call(request);
		String auth = response.getString("result");
		if (auth != null && !auth.isEmpty()) {
			this.setAuth(auth);
			logger.info("login zabbix success!");
			return true;
		}
		logger.info("login zabbix failed!");
		return false;
	}
	/**
	 * 查询ITEMS
	 * @param hostName  hostIP
	 * @param searchKey 查询KEY
	 * @param groupName  group名
	 * @return item列表
	 * @throws Exception 异常
	 */
	public JSONObject queryItems(String hostName,String searchKey,String groupName)throws Exception{
		JSONObject response = null;
		JSONObject search = new JSONObject();
		logger.info("queryItems--searchKey: "+searchKey+" hostName:"+hostName+"  groupName: "+groupName);
	    search.put("key_", searchKey);
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("item.get")
				.paramEntry("output", "extend")
				.paramEntry("host", hostName)
				.paramEntry("search", search)
				//.paramEntry("group", groupName)
				.build();
		 response = call(request);
		return response;
	}
	/**
	 * 查询HOST
	 * @param hostName  hostIP
	 * @return HOST列表
	 * @throws Exception 异常
	 */
	public JSONObject queryHost(String hostName)throws Exception{
		JSONObject response = null;
		if(login()){
			logger.info("queryHost--hostName: "+hostName);
			 JSONObject search = new JSONObject();
			 search.put("host", hostName);
			ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("host.get")
					.paramEntry("output", "extend")
					.paramEntry("filter",search)
					.build();
			 response = call(request);
		}
		return response;
	}
	/**
	 * 查询Applications
	 * @param hostId  hostId
	 * @param name 查询名
	 * @return Applications列表
	 * @throws Exception 异常
	 */
	public JSONObject queryApplications(String hostId,String name)throws Exception{
		JSONObject response = null;
		JSONObject search = new JSONObject();
		search.put("key", name);
		logger.info("queryApplications--hostId: "+hostId);
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("application.get")
				.paramEntry("output", "extend")
				.paramEntry("hostids",hostId)
				.paramEntry("filter",search)
				.build();
		 response = call(request);
		 logger.info(String.format("queryApplications response:%s", response.toJSONString()));
		return response;
	}
	/**
	 * hostinterface.get 
	 * @param hostId hostid
	 * @return hostinterface list
	 * @throws Exception
	 */
	public JSONObject queryHostInterface(String hostId)throws Exception{
	JSONObject response = null;
		logger.info("queryHostInterface--hostId: "+hostId);
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("hostinterface.get")
				.paramEntry("output", "extend")
				.paramEntry("hostids",hostId)
				.build();
		 response = call(request);
		 logger.info(String.format("queryHostInterface response:%s", response.toJSONString()));
		return response;
	}
	
	
	public JSONObject call(ZabbixRequest request) throws URISyntaxException {
		if (request.getAuth() == null) {
			request.setAuth(auth);
		}
		String url =env.getProperty("ZABBIX_URL");
		try {
			HttpUriRequest httpRequest = org.apache.http.client.methods.RequestBuilder
					.post().setUri(new URI(url.trim()))
					.addHeader("Content-Type", "application/json")
					.setEntity(new StringEntity(JSON.toJSONString(request),"utf-8"))
					.build();
			CloseableHttpClient httpClient=HttpClients.custom().build();
			CloseableHttpResponse response = httpClient.execute(httpRequest);
			HttpEntity entity = response.getEntity();
			byte[] data = EntityUtils.toByteArray(entity);
			return (JSONObject) JSON.parse(data);
		} catch (IOException e) {
			throw new RuntimeException("DefaultZabbixApi call exception!", e);
		}
	}
	 /**
	    * 将入参转为需要的格式
	    * @param user_time
	    * @return
	    * @throws Exception 
	    */
	   public static String dateToTimestamp(String time_from) throws Exception {
		   Calendar calendar = Calendar.getInstance();
		   switch (time_from) {
		   case "d":
			   calendar.add(Calendar.DAY_OF_YEAR, -1); 
			   break;
	       case "w":
	    	   calendar.add(Calendar.WEEK_OF_YEAR, -1);
	    	   break;
	       case "m":
	    	   calendar.add(Calendar.MONTH, -1);
			   break;
	       case "h":
	    	   calendar.add(Calendar.HOUR,-12);
			   break;
			default:
				calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
				break;
			}
		   
	       String re_time = null;
	       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	       Date d;
	       d = sdf.parse(sdf.format(calendar.getTime()));
		   long l = d.getTime();
		   String str = String.valueOf(l);
		   re_time = str.substring(0, 10);
	       return re_time;
	   }
	/**
	 * 根据监控项id和主机id查询监控项
	 * @param monitorKeys (必须)监控项keys
	 * @param hostids 主机ids
	 * @param outputs 输出栏位名称
	 * @return 符合条件的items json
	 * @throws MonitorException
	 */
	public JSONObject queryItemsByKeysHostids(Collection monitorKeys, Collection hostids,
			String... outputs) throws MonitorException {

		try {
			JSONObject filter = new JSONObject();
			filter.put("key_", monitorKeys);
			if (CollectionUtils.isNotEmpty(hostids)) {
				filter.put("hostid", hostids);
			}
			ZabbixRequestBuilder builder = ZabbixRequestBuilder.newBuilder().method("item.get")//
					.paramEntry("output", ArrayUtils.isEmpty(outputs) ? "extend" : outputs)//
					.paramEntry("filter", filter)//
					.paramEntry("selectInterfaces", new String[]{"interfaceid", "hostid", "ip", "type"})
					.paramEntry("selectTriggers", new String[]{"triggerid", "expression", "state", "status", "value"})
					.paramEntry("selectHosts", new String[] { "host", "hostid" });//
			ZabbixRequest request =	builder.build();
			logger.info(
					String.format("queryItemsByKeysHostids >>>>request:%s", ToStringBuilder.reflectionToString(request)));
			JSONObject json = call(request);
			logger.info(String.format("queryItemsByKeysHostids << monitorKeys, String... outputs) throws MonitorException{

		try {
			JSONObject filter = new JSONObject();
			filter.put("key_", monitorKeys);
			ZabbixRequestBuilder builder = ZabbixRequestBuilder.newBuilder().method("item.get")//
					.paramEntry("output", ArrayUtils.isEmpty(outputs) ? "extend" : outputs)//
					.paramEntry("filter", filter)//
					.paramEntry("templated", true);//
			ZabbixRequest request =	builder.build();
			logger.info(
					String.format("queryTemplateItemsByKeys >>>>request:%s", ToStringBuilder.reflectionToString(request)));
			JSONObject json = call(request);
			logger.info(String.format("queryTemplateItemsByKeys << hostNames, String... outputs) throws MonitorException {
		try {
			JSONObject jsonHostInterfaces = queryInterfacesByHostnames(hostNames, "hostid");
			
			JSONArray hostArray = jsonHostInterfaces.getJSONArray("result");
			Set hostids = new HashSet();
			for(int i = 0; i< hostArray.size(); i++){
				hostids.add(hostArray.getJSONObject(i).getString("hostid"));
			}
			if(CollectionUtils.isEmpty(hostids)){
				throw new MonitorException("主机不存在,HostNames : " + hostNames);
			}
			JSONObject filter = new JSONObject();
			filter.put("hostid", hostids);
			ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("host.get")//
					.paramEntry("filter", filter)//
					.paramEntry("selectInterfaces", new String[]{"interfaceid", "ip", "type", "hostid"})//
					.paramEntry("output", ArrayUtils.isEmpty(outputs) ? "extend" : outputs)//
					.build();
			logger.info(String.format("queryHostsByHostnames >>>>request:%s", ToStringBuilder.reflectionToString(request)));
			JSONObject json = call(request);

			logger.info(String.format("queryHostsByHostnames << out = Arrays.asList(name);
			List output = Arrays.asList("itemid","name","key_");
			Map filter = new HashMap();
			filter.put("host", out);
			ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("template.get")
					.paramEntry("output", "extend")
					.paramEntry("selectItems", output)
					.paramEntry("filter", filter)
					.build();
			 response = call(request);
		}
		return response;
	}
	/**
	 * 通过itemid,查询模板详情
	 * @param name
	 * @return
	 * @throws URISyntaxException 
	 */
	public JSONObject queryTemplateByItemids(List itemids, Collection hostids, String...outputs) throws URISyntaxException{
		JSONObject response = null;
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("template.get")
				.paramEntry("itemids", itemids)
				.paramEntry("hostids", hostids)
				.paramEntry("selectHosts", new String[]{"hostid", "host"})
				.paramEntry("output", ArrayUtils.isEmpty(outputs) ? "extend" : outputs)
				.build();
		logger.info(String.format("queryTemplateByItemids >>>>request:%s", ToStringBuilder.reflectionToString(request)));
		response = call(request);
		logger.info(String.format("queryTemplateByItemids << hostNames, String... outputs) throws MonitorException{
		try {
			JSONObject filter = new JSONObject();
			filter.put("ip", hostNames);
			ZabbixRequest request = ZabbixRequestBuilder.newBuilder().method("hostinterface.get")//
					.paramEntry("filter", filter)//
					.paramEntry("output", ArrayUtils.isEmpty(outputs) ? "extend" : outputs)//
					.build();
			logger.info(String.format("queryInterfacesByHostnames >>>>request:%s", ToStringBuilder.reflectionToString(request)));
			JSONObject json = call(request);

			logger.info(String.format("queryInterfacesByHostnames <<


api文档   https://www.zabbix.com/documentation/2.2/manual/api

docs   http://www.zabbix.org/wiki/Docs/api/libraries

你可能感兴趣的:(zabbix)