Commit cad57361 authored by gaozhentao's avatar gaozhentao

新增微信告警(注:微信告警未调试成功)

parent fbafd185
......@@ -107,4 +107,18 @@ public class ReliabilityApi {
return manager.getStatistics();
}
@GetMapping("wxAlarm")
public boolean wxAlarm() {
return manager.wxAlarm();
}
@PostMapping("changeSwitch")
public Map changeSwitch(@RequestBody String json) {
return manager.changeSwitch(json);
}
@GetMapping("getSwitch")
public Map getSwitch() {
return manager.getSwitch();
}
}
......@@ -8,6 +8,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
public class InitAscynTaskThreadPoolConfig {
......@@ -35,4 +37,13 @@ public class InitAscynTaskThreadPoolConfig {
executor.setMaxPoolSize(MAX_POOL_SIZE);
return executor;
}
@Bean(name = "monitorLink" )
public Executor getLinkState() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(CORE_POOL_SIZE);
executor.setMaxPoolSize(MAX_POOL_SIZE);
executor.initialize();
return executor;
}
}
package com.yingxin.prms.config.filter;
import com.yingxin.prms.service.dao.CassandraDaoImpl;
import com.yingxin.prms.utils.TokenUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -25,7 +26,22 @@ import java.util.Map;
public class TokenInterceptor implements HandlerInterceptor {
private Map<String,String> tokenList;
/* 告警通知开关 默认关闭,服务启动会重新赋值 */
public static boolean currSwitch ;
@Autowired
private CassandraDaoImpl cassandraDao;
@Bean
public boolean getcurrSwitch(){
Map switchMap = cassandraDao.getSwitch();
if(switchMap.get("switch").equals("open")){
currSwitch = true;
}else{
currSwitch = false;
}
return currSwitch;
}
@Bean
public Map<String,String> getTokenList(){
tokenList = new HashMap<>();
......
......@@ -47,7 +47,8 @@ public class WebConfiguration implements WebMvcConfigurer {
.excludePathPatterns("/js/**")
.excludePathPatterns("/index.html")
.excludePathPatterns("/rest/rel/login")
.excludePathPatterns("/rest/rel/selectTopology");
.excludePathPatterns("/rest/rel/changeSwitch")
.excludePathPatterns("/rest/rel/getSwitch");
WebMvcConfigurer.super.addInterceptors(registry);
}
......
......@@ -105,4 +105,19 @@ public class AlarmLog {
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
@Override
public String toString() {
return "AlarmLog{" +
"serialnum='" + serialnum + '\'' +
", ip='" + ip + '\'' +
", port='" + port + '\'' +
", alarmLevel='" + alarmLevel + '\'' +
", alarmMessage='" + alarmMessage + '\'' +
", clusterName='" + clusterName + '\'' +
", alatime='" + alatime + '\'' +
", rectime='" + rectime + '\'' +
", state='" + state + '\'' +
'}';
}
}
package com.yingxin.prms.dto.wx;
/**
* Created by gaoxiang on 2017/12/29.
* 微信推送bean
*/
public class AccessTokenRequset {
/*url*/
private String accessTokenUrl;
/*公司ID*/
private String corpid;
/*秘钥*/
private String corpsecret;
public String getAccessTokenUrl() {
return accessTokenUrl;
}
public void setAccessTokenUrl(String accessTokenUrl) {
this.accessTokenUrl = accessTokenUrl;
}
public String getCorpid() {
return corpid;
}
public void setCorpid(String corpid) {
this.corpid = corpid;
}
public String getCorpsecret() {
return corpsecret;
}
public void setCorpsecret(String corpsecret) {
this.corpsecret = corpsecret;
}
public AccessTokenRequset(String accessTokenUrl, String corpid, String corpsecret) {
super();
this.accessTokenUrl = accessTokenUrl;
this.corpid = corpid;
this.corpsecret = corpsecret;
}
public AccessTokenRequset() {
super();
}
@Override
public String toString() {
return "AccessTokenRequset [accessTokenUrl=" + accessTokenUrl + ", corpid=" + corpid + ", corpsecret="
+ corpsecret + "]";
}
}
package com.yingxin.prms.dto.wx;
/**
* Created by gaoxiang on 2017/12/29.
*/
public class AccessTokenResponse {
private int errcode;
private String errmsg;
private String access_token;
private int expires_in;
public int getErrcode() {
return errcode;
}
public void setErrcode(int errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expires_in = expires_in;
}
public AccessTokenResponse(String access_token, int expires_in) {
super();
this.access_token = access_token;
this.expires_in = expires_in;
}
public AccessTokenResponse() {
super();
}
@Override
public String toString() {
return "AccessTokenResponse [access_token=" + access_token + ", expires_in=" + expires_in + "]";
}
}
package com.yingxin.prms.dto.wx;
/**
* description//TODO
*
* @author gaozhentao
* @version 1.0
* @date 2019/10/14
*/
public class MonitorConfig {
private String agentId;
private String corpid;
private String corpsecret;
private String alarmMsg;
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public MonitorConfig() {}
public String getAgentId() {
return agentId;
}
public void setAgentId(String agentId) {
this.agentId = agentId;
}
public String getCorpid() {
return corpid;
}
public void setCorpid(String corpid) {
this.corpid = corpid;
}
public String getCorpsecret() {
return corpsecret;
}
public void setCorpsecret(String corpsecret) {
this.corpsecret = corpsecret;
}
public String getAlarmMsg() {
return alarmMsg;
}
public void setAlarmMsg(String alarmMsg) {
this.alarmMsg = alarmMsg;
}
@Override
public String toString() {
return "MonitorConfig{" +
"agentId='" + agentId + '\'' +
", corpid='" + corpid + '\'' +
", corpsecret='" + corpsecret + '\'' +
", alarmMsg='" + alarmMsg + '\'' +
", url='" + url + '\'' +
'}';
}
}
package com.yingxin.prms.dto.wx;
/**
* 微信返回结果模型
*/
public class WxResponseBean {
private String errcode;
private String errmsg;
private String invaliduser;
public String getInvaliduser() {
return invaliduser;
}
public void setInvaliduser(String invaliduser) {
this.invaliduser = invaliduser;
}
public String getErrcode() {
return errcode;
}
public void setErrcode(String errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
@Override
public String toString() {
return "WxResponseBean [errcode=" + errcode + ", errmsg=" + errmsg + "]";
}
}
package com.yingxin.prms.service.asyncTask;
import com.yingxin.prms.config.Constant;
import com.yingxin.prms.config.filter.TokenInterceptor;
import com.yingxin.prms.domain.AlarmLog;
import com.yingxin.prms.domain.Server_Host_Info;
import com.yingxin.prms.dto.wx.MonitorConfig;
import com.yingxin.prms.service.dao.CassandraDaoImpl;
import com.yingxin.prms.utils.MonitorUtil;
import com.yingxin.prms.utils.TimeUtil;
import org.kairosdb.client.HttpClient;
import org.kairosdb.client.builder.*;
......@@ -11,10 +14,12 @@ import org.kairosdb.client.response.QueryResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;
......@@ -25,22 +30,46 @@ public class AlarmTask {
private static Logger logger = LoggerFactory.getLogger(AlarmTask.class);
private final HttpClient client;
/*企业ID*/
@Value("${corpid}")
public String corpid;
/*管理组凭证密钥*/
@Value("${corpsecret}")
public String corpsecret;
/*应用代理ID*/
@Value("${agentId}")
public String agentId;
/*wx告警地址*/
@Value("${wxurl}")
public String wxurl;
@Autowired
private CassandraDaoImpl cassandraDao;
public static int kk = 0;
@Autowired
public AlarmTask(HttpClient client) {
this.client = client;
}
@Async("asyncTaskPool")
@Async("monitorLink")
public void doTask(Server_Host_Info hostInfo) {
String tag = hostInfo.getHost_ip() + ":" + hostInfo.getHost_port();
long begin = System.currentTimeMillis();
/** 微信监控信息对象 */
MonitorConfig monitorConfig = new MonitorConfig();
monitorConfig.setAgentId(agentId);
monitorConfig.setCorpid(corpid);
monitorConfig.setCorpsecret(corpsecret);
monitorConfig.setUrl(wxurl);
Aggregator aggregator5Min = AggregatorFactory.createSumAggregator(5, TimeUnit.MINUTES);
Aggregator aggregator1Min = AggregatorFactory.createSumAggregator(1, TimeUnit.MINUTES);
String tag = hostInfo.getService_path();
QueryBuilder query5Min = createQuery(5, TimeUnit.MINUTES, "heartbeat", tag, aggregator5Min);
QueryBuilder query1Min = createQuery(1, TimeUnit.MINUTES, "heartbeat", tag, aggregator1Min);
try {
......@@ -74,7 +103,8 @@ public class AlarmTask {
AlarmLog alarmCheck = cassandraDao.checkAlarm(hostInfo.getCluster_name(),hostInfo.getHost_ip(), String.valueOf(hostInfo.getHost_port()));
String msg = "";
boolean flag = true;
if (faultCount5Min != 0) {
if (faultCount5Min != 0 ) {
/* 不稳定告警 */
alarmLog.setAlatime(TimeUtil.getDate());
alarmLog.setState(Constant.ALARM_ING);
......@@ -86,7 +116,7 @@ public class AlarmTask {
flag = false;
}
if(faultCount1Min >= correctCount1Min) {
if(faultCount1Min >= correctCount1Min || dataPoints5Min.size() == 0 ) {
/* 宕机告警 */
alarmLog.setAlatime(TimeUtil.getDate());
alarmLog.setState(Constant.ALARM_ING);
......@@ -97,20 +127,37 @@ public class AlarmTask {
alarmLog.setAlarmMessage(msg);
flag = false;
}
if(flag){
if(alarmCheck != null){
/* 如果存在告警 则恢复 */
cassandraDao.updateAlarm(alarmCheck.getSerialnum(),TimeUtil.getDate());
String recoveryMsg = alarmCheck.getClusterName() + " " + alarmCheck.getIp()
+ ":" + alarmCheck.getPort() + ",告警已恢复";
monitorConfig.setAlarmMsg("【告警恢复】"+recoveryMsg);
if(TokenInterceptor.currSwitch){
MonitorUtil.wxAlarm(monitorConfig);
}
}
}else{
if(alarmCheck == null){
/* 如果不存在告警 新增数据 */
cassandraDao.insertAlarm(alarmLog);
System.out.println("kk:"+(++kk));
monitorConfig.setAlarmMsg(alarmLog.getAlarmMessage());
if(TokenInterceptor.currSwitch){
MonitorUtil.wxAlarm(monitorConfig);
}
}else {
/* 如果告警发生变化 回复时间变成告警时间 */
if(!alarmCheck.getAlarmLevel().equals(alarmLog.getAlarmLevel())) {
cassandraDao.updateAlarm(alarmCheck.getSerialnum(),"------");
cassandraDao.insertAlarm(alarmLog);
monitorConfig.setAlarmMsg("【告警内容更新】"+alarmLog.getAlarmMessage());
if(TokenInterceptor.currSwitch){
MonitorUtil.wxAlarm(monitorConfig);
}
}
}
}
......@@ -118,6 +165,8 @@ public class AlarmTask {
logger.error("告警校验发生错误。inMonitoring返回false");
logger.error(e.getMessage());
}
long end = System.currentTimeMillis()-begin;
}
private QueryBuilder createQuery(int start, TimeUnit timeUnit, String metric, String tag, Aggregator aggregator) {
......
......@@ -49,16 +49,17 @@ public class HttpTask extends BasicTask{
long dur = 0;
long start = System.currentTimeMillis();
try {
if (hostInfo.getService_method().equals("post") && !hostInfo.getCluster_name().equals("网证开通接口")) {
if(hostInfo.getRequest_body()== null){
map = SendHttpUtil.doPost(hostInfo.getService_path(),"");
}else {
long getStart = System.currentTimeMillis();
map = SendHttpUtil.doPost(hostInfo.getService_path(),hostInfo.getRequest_body());
}
}
if (hostInfo.getService_method().equals("get")) {
long getStart = System.currentTimeMillis();
map = SendHttpUtil.doGet(hostInfo.getService_path());
}
dur = System.currentTimeMillis() - start;
......
......@@ -3,13 +3,11 @@ package com.yingxin.prms.service.business;
import com.yingxin.prms.config.filter.TokenInterceptor;
import com.yingxin.prms.domain.*;
import com.yingxin.prms.dto.*;
import com.yingxin.prms.dto.wx.MonitorConfig;
import com.yingxin.prms.service.asyncTask.QueryHostStatusTask;
import com.yingxin.prms.service.dao.CassandraDaoImpl;
import com.yingxin.prms.service.dao.FlowDaoImpl;
import com.yingxin.prms.utils.CurveFittingMethod;
import com.yingxin.prms.utils.SendHttpUtil;
import com.yingxin.prms.utils.TimeUtil;
import com.yingxin.prms.utils.TokenUtil;
import com.yingxin.prms.utils.*;
import net.sf.json.JSONObject;
import org.kairosdb.client.HttpClient;
import org.kairosdb.client.builder.*;
......@@ -38,6 +36,22 @@ public class Manager {
@Value("${pointNumber}")
private int pointNumber;
/*企业ID*/
@Value("${corpid}")
public String corpid;
/*管理组凭证密钥*/
@Value("${corpsecret}")
public String corpsecret;
/*应用代理ID*/
@Value("${agentId}")
public String agentId;
/*wx告警地址*/
@Value("${wxurl}")
public String wxurl;
private final AuthModeAndHostList authModeAndHostList;
private final CassandraDaoImpl cassandraDao;
......@@ -556,6 +570,49 @@ public class Manager {
public boolean wxAlarm(){
/** 微信监控信息对象 */
MonitorConfig monitorConfig = new MonitorConfig();
monitorConfig.setAgentId(agentId);
monitorConfig.setCorpid(corpid);
monitorConfig.setCorpsecret(corpsecret);
monitorConfig.setUrl(wxurl);
String msg ="【告警测试】"+ "依图"+ " " + "192.168.56.15"
+ ":" +"22" + ",告警已恢复";
monitorConfig.setAlarmMsg(msg);
return MonitorUtil.wxAlarm(monitorConfig);
}
public Map changeSwitch(String json) {
JSONObject jsonObject = JSONObject.fromObject(json);
String currState = jsonObject.getString("state");
boolean flag =false;
if(currState.equals("close")){
flag = cassandraDao.changeSwitch("open");
TokenInterceptor.currSwitch = true;
}else if(currState.equals("open")){
flag = cassandraDao.changeSwitch("close");
TokenInterceptor.currSwitch = false;
}
Map map = new HashMap();
map.put("state",flag);
return map;
}
public Map getSwitch() {
Map map = new HashMap();
if(TokenInterceptor.currSwitch){
map.put("switch","open");
}else{
map.put("switch","close");
}
return map;
}
/*
public Map selectClusterStatus() {
List<Server_Host_Info> host_info_List = authModeAndHostList.getClusterBeMonitoredList();
......
......@@ -70,11 +70,13 @@ public class CassandraDaoImpl {
public boolean updateAlarm(String serialnum,String time) {
String cql="update ctid_prof.alarm_log set rectime = '"+time+"' , state = '" +Constant.ALARM_RECOVERY +"', alarm_level = '"+Constant.ALARM_OK+"' where serialnum = '"+serialnum +"'";
System.out.println("cql:"+cql);
return template.getCqlOperations().execute(cql);
}
public void insertAlarm(AlarmLog alarmLog) {
String cql ="INSERT INTO ctid_prof.alarm_log (serialnum, alarm_level, alarm_message, alatime, cluster_name, ip, port, rectime, state)" +
"VALUES('"+alarmLog.getSerialnum()+"', '"+alarmLog.getAlarmLevel()+"', '"+alarmLog.getAlarmMessage()+"', '"+alarmLog.getAlatime()+"', '"+alarmLog.getClusterName()+"', '"+alarmLog.getIp()+"', '"+alarmLog.getPort()+"', '"+alarmLog.getRectime()+"', '"+alarmLog.getState()+"');";
System.out.println("cql:"+cql);
template.getCqlOperations().execute(cql);
}
public Map getAlarmLogSize() {
......@@ -96,4 +98,20 @@ public class CassandraDaoImpl {
String cql = "select * from server_host_info where cluster_name = '平台业务实时统计服务' allow filtering";
return template.selectOne(cql, Server_Host_Info.class);
}
public AlarmLog findAlarmBySernum(String serialnum) {
String cql="SELECT * FROM ctid_prof.alarm_log where serialnum = '"+serialnum +"'";
return template.selectOne(cql, AlarmLog.class);
}
public boolean changeSwitch(String state) {
String cql ="UPDATE ctid_prof.alarm_switch SET switch='"+state+"'" +
"WHERE username='admin';";
return template.getCqlOperations().execute(cql);
}
public Map getSwitch() {
String cql ="SELECT * FROM ctid_prof.alarm_switch WHERE username='admin';";
return template.selectOne(cql,Map.class);
}
}
......@@ -12,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
......@@ -55,7 +56,7 @@ public class Schedule {
logger.info("开始告警判断");
List<Server_Host_Info> server_host_infos = list.getClusterBeMonitoredList();
for (Server_Host_Info hostInfo : server_host_infos) {
alarmTask.doTask(hostInfo);
alarmTask.doTask(hostInfo);
}
}
}
package com.yingxin.prms.utils;
import com.yingxin.prms.dto.wx.AccessTokenRequset;
import com.yingxin.prms.dto.wx.AccessTokenResponse;
import com.yingxin.prms.dto.wx.MonitorConfig;
import com.yingxin.prms.dto.wx.WxResponseBean;
public class MonitorUtil {
public static boolean wxAlarm(MonitorConfig monitorConfig){
AccessTokenRequset atrequset = new AccessTokenRequset(monitorConfig.getUrl(), monitorConfig.getCorpid(), monitorConfig.getCorpsecret());
AccessTokenResponse asresponse = null;
String sendjson = "{\n" +
" \"touser\" : \"@all\",\n" +
" \"toparty\" : \" \",\n" +
" \"totag\" : \" \",\n" +
" \"msgtype\" : \"text\",\n" +
" \"agentid\" : "+monitorConfig.getAgentId()+",\n" +
" \"text\" : {\n" +
" \"content\" : \""+monitorConfig.getAlarmMsg()+"\"\n" +
" },\n" +
" \"safe\":0,\n" +
" \"enable_id_trans\": 0\n" +
"}";
try {
asresponse = SendHttpUtil.getAccessToken(atrequset);
// 微信推送消息体,不可更改
WxResponseBean wx = SendHttpUtil.sendTextMessage(asresponse, sendjson);
return true;
} catch (Exception e) {
return false;
}
}
}
package com.yingxin.prms.utils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yingxin.prms.dto.wx.AccessTokenRequset;
import com.yingxin.prms.dto.wx.AccessTokenResponse;
import com.yingxin.prms.dto.wx.WxResponseBean;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
......@@ -15,9 +21,14 @@ import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
......@@ -65,7 +76,7 @@ public class SendHttpUtil {
map.put("body",EntityUtils.toString(responseEntity));
}
}catch (ConnectException e){
logger.error(uri+"请求超时");
// logger.error(uri+"请求超时");
}catch (ConnectTimeoutException e){
}
......@@ -95,13 +106,20 @@ public class SendHttpUtil {
Map<String,String> map = new HashMap();
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost(uri);
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(3000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(3000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
httpPost.setConfig(requestConfig);
StringEntity entity = new StringEntity(body, "UTF-8");
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);
......@@ -121,8 +139,10 @@ public class SendHttpUtil {
map.put("body",EntityUtils.toString(responseEntity, "utf-8"));
}
// 从响应模型中获取响应实体
}catch (ConnectException e){
logger.error(uri+"请求超时");
}catch (ConnectTimeoutException e){
// logger.error(uri+"连接超时");
} catch (ConnectException e){
// logger.error(uri+"请求超时");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
......@@ -148,4 +168,154 @@ public class SendHttpUtil {
}
}
/**
* 获取微信凭证
* @param accessTokenRequset
* @return
*/
public static AccessTokenResponse getAccessToken(AccessTokenRequset accessTokenRequset) {
try {
String s = sendGet(accessTokenRequset.getAccessTokenUrl(), "corpid=" + accessTokenRequset.getCorpid() + "&corpsecret=" + accessTokenRequset.getCorpsecret());
ObjectMapper mapper = new ObjectMapper();
AccessTokenResponse accessTokenResponse = mapper.readValue(s, AccessTokenResponse.class);
return accessTokenResponse;
} catch (Exception e) {
return null;
}
}
/**
* 发送信息
* @param accessTokenResponse
* @param sendjson
* @return
*/
public static WxResponseBean sendTextMessage(AccessTokenResponse accessTokenResponse, String sendjson) {
ObjectMapper mapper = new ObjectMapper();
String result = sendPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessTokenResponse.getAccess_token(), sendjson);
WxResponseBean wxResultMassage = new WxResponseBean();
try {
wxResultMassage = mapper.readValue(result, WxResponseBean.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return wxResultMassage;
}
/**
* 与微信服务建立连接
*
* @param url 请求地址
* @param param 请求参数
* @return
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
//URL设置超时时间
connection.setConnectTimeout(1000);
connection.setReadTimeout(1000);
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
// Map<String, List<String>> map = connection.getHeaderFields();
// // 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("发送GET请求出现异常!" + e);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
......@@ -40,8 +40,8 @@ demo:
dailyAuthCount:
url: "http://15.1.3.8:9000/acl/v1/dailyCount"
ascynTaskThreadPool:
corePoolSize: 24
maxPoolSize: 36
corePoolSize: 60
maxPoolSize: 80
clusterStatusPoolSize: 16
alarm:
ip: "15.2.249.205"
......@@ -51,3 +51,13 @@ alarm:
tokeTime: 1200000
pointNumber: 60
#微信告警
#应用代理ID
agentId: 1000004
#管理组凭证密钥
corpsecret: 0gXvh18To60vLpw1wlPO4ncshvZjDKR0vaUuHAeDOb0
#wx告警地址
wxurl: https://qyapi.weixin.qq.com/cgi-bin/gettoken
#企业ID
corpid: wwb8a34ddb02c87228
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment