Ngnix服务器在线健康检查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39433171/article/details/82012899

首先了解我的这个业务需求,将这个做成一个定时器,固定间隔时间检查线上服务器Upstream的status,因为我是整合在xxl-job里面,所以不用像spring那样还得配置各种东西,在这里我只写代码,想要运行的朋友可以直接写个main方法调用check()就好了。(这个用行内话就是说,这个实例我写死了,手动加地址,后期我会改写一下,根据自己公司建表重新写一份比较灵活的示例)先看示例图片,声明:一下图片是服务器地址+/stats得来的,即–http:/xxx.xxxxxxx.com/stats
附上此文用到的企业微信开发地址,点我点我,快点我

这里写图片描述
我们要做的健康检查就是,读取上述图片中 Status一栏数据,正常在线服务器为up,宕机的为down,所以,我们只需要获得此页面,并读取status为down的即可。
接下来是代码实现部分。
第一步建立工具类:

public class HttpRequestHelper {
/**
     * GET发送请求
     * @param url--请求地址
     * @param codePage--数据编码
     * @return
     * @throws Exception
     */
    public  static String getData(String url, String codePage) throws Exception {
        final HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30 * 1000);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000);
        final GetMethod method = new GetMethod(url);
        String result = "";
        try {
            httpClient.executeMethod(method);
            result = new String(method.getResponseBody(), codePage);
        } catch (final Exception e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
        return result;
    }
    /**
     * post请求发送数据
     * @return
     * @throws Exception
     */
    public static String paramsPostJson(String sendurl,String params) throws Exception{
        StringBuffer buffer = new StringBuffer();

        try {
               URL uploadServlet = new URL(sendurl);
               BufferedReader reader = null;
               String strMessage = "";
               HttpURLConnection servletConnection = (HttpURLConnection) uploadServlet
                      .openConnection();
               // 设置连接参数
               servletConnection.setRequestMethod("POST");
               servletConnection.setDoOutput(true);
               servletConnection.setDoInput(true);
               servletConnection.setAllowUserInteraction(true);
               servletConnection.setRequestProperty("Content-type", "application/json");  
               // 开启流,写入XML数据
               OutputStream output = servletConnection.getOutputStream();
               output.write(params.toString().getBytes("UTF-8"));
               output.flush();
               output.close();
               // 获取返回的数据
               InputStream inputStream = servletConnection.getInputStream();
               reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
               while ((strMessage = reader.readLine()) != null) {
                  buffer.append(strMessage);
               }

        } catch (java.net.ConnectException e) {
                e.printStackTrace();
        }
        return buffer.toString();
    }
}

第二步,一个方法类,本类主要是发送GET请求,获取一图html文档结构,然后做html解析,拿到想要的信息,并以post请求方式将信息发送至管理人员的企业微信

public static void check() throws Exception{
         String[] checkUrlArr={"http://xxx.x.xxx/stats"};
         String[] serverNameArr={"【XXX】"};
        for(int checkNum=0;checkNum<checkUrlArr.length;checkNum++){
            String content="";
            String json = HttpRequestHelper.getData(checkUrlArr[checkNum], "utf-8");//返回一个html文档结构,展现在页面就是上图内容
            Document doc = Jsoup.parse(json);//jsoup解析thml,封装成Document类型
            Elements links = doc.getElementsByTag("tr");//拿到tr
            for(int i=0;i<links.size();i++){
                String str =links.get(i).toString();//将tr转换成字符串
                if(str.indexOf("XXX")>-1 && str.indexOf("down")>-1){//判断位置,
                    Elements tdEls=links.get(i).getElementsByTag("td");//拿到td
                    LinkedMap checkMap=new LinkedMap();
                        for (int j=0;j<tdEls.size();j++) {
                            if(j==1){
                                checkMap.put("Upstream", tdEls.get(j).text());//当下标为1的时候,添加Upstream
                            }
                            if(j==2){
                                checkMap.put("serverName", tdEls.get(j).text());//当下标为2的时候,添加serverName
                            }
                            if(j==3){
                                checkMap.put("serverStatus", tdEls.get(j).text());//当下标为3的时候,添加serverName
                            }
                            checkMap.put("checkUrl", checkUrlArr[checkNum]);
                            checkMap.put("projectName", serverNameArr[checkNum]);
                        }
                        JSONObject jsonObject =  JSONObject.fromObject(checkMap);//map转json                    
                        content+= jsonObject.toString();//将staus为down的upstream等信息放进来
                   }
            }
            if(!StringUtils.isEmpty(content)){//如果content不为空
String accessJson=HttpRequestHelper.getData("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=自己获取(我这里两个是公司给我的)&corpsecret=自己获取","utf-8");
                Map<String, Object> accessMap = new HashMap<String, Object>();
                Gson g = new Gson();
                accessMap = g.fromJson(accessJson, accessMap.getClass());
                String sendUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessMap.get("access_token");//微信接口发送企业微信管理人员的微信号
                Map<String,String> map1 =new HashMap<String,String>();
                map1.put("content", content);
                LinkedMap map=new LinkedMap();
                map.put("touser", "某某某|某某某|某某某");//user多个用|隔开
                map.put("msgtype", "text");//msg类型
                map.put("agentid", 自己获取,是一个7位数);//企业应用的id,整型,可在应用的设置页面查看 
                map.put("text", new JSONObject().fromObject(map1));//文本信息,content
                map.put("safe", 0);//0表示否,1表示是,默认0  
                String param=JacksonHelper.toJSON(map);//map转json
                String result=HttpRequestHelper.paramsPostJson(sendUrl,param)//post发送数据
            }
        }
    }

以上就是整个服务器健康检查的整个代码,按理说把该替换的信息替换掉,即可直接运行。

猜你喜欢

转载自blog.csdn.net/weixin_39433171/article/details/82012899