Spring Boot Admin2 自定义异常监控
创始人
2024-02-16 05:05:54

其他相关文章:

  1. Spring Boot Admin 参考指南
  2. SpringBoot Admin服务离线、不显示健康信息的问题
  3. Spring Boot Admin2 @EnableAdminServer的加载
  4. Spring Boot Admin2 AdminServerAutoConfiguration详解
  5. Spring Boot Admin2 实例状态监控详解
  6. Spring Boot Admin2 自定义JVM监控通知

有时候客户往往会先于我们发现产品的异常,经常是他们跟我们反馈,为了改变这种状况,我们需要监控服务发生的各种异常。而正好SBA2 提供了HTTP请求相关的异常统计指标。那么我们经过适当的设计就可以达到每次有异常发生的时候就发送通知,实现原理就是:查询的最新异常累计值大于原有值时,表示新发生异常

看下提醒效果:

在这里插入图片描述

同样的马上代码:

NotifierAutoConfiguration.exceptionAlarm

@Bean(initMethod = "start", destroyMethod = "stop")
@ConditionalOnProperty(prefix = "spring.boot.admin.notify.exception", name = "enabled", havingValue = "true")
@ConfigurationProperties("spring.boot.admin.notify.exception")
@Lazy(false)
public ExceptionAlarm exceptionAlarm(InstanceRepository repository, AlarmMessage alarmMessage) {return new ExceptionAlarm(repository, alarmMessage);
}

ExceptionAlarm

@Slf4j
public class ExceptionAlarm {private final RestTemplate restTemplate = new RestTemplate();private Scheduler scheduler;private Disposable subscription;private InstanceRepository repository;private AlarmMessage alarmMessage;/*** 开关*/private boolean enabled = true;/*** 检测频率,秒*/private long interval = 10;/*** 排除异常*/private String exclude = "None,BizException";/*** 排除实例*/private String excludeInstances = "";/*** 提醒模版*/private final String ALARM_TPL = "服务实例【%s】,发生异常【%s】";/*** 最后一次检测时的异常次数*/private final Map> instanceCount = new HashMap<>();public ExceptionAlarm(InstanceRepository repository, AlarmMessage alarmMessage) {this.repository = repository;this.alarmMessage = alarmMessage;}private void checkFn(Long aLong) {if (!enabled) {return;}log.debug("check exception for all instances");//检查所有实例repository.findAll().filter(instance -> !excludeInstances.contains(instance.getRegistration().getName())).map(instance -> {String instanceName = instance.getRegistration().getName();List exceptionList = getExceptionTag(instance);for (String exception : exceptionList) {Integer value = getValue(instance, exception);Integer lastValue = instanceCount.getOrDefault(instanceName, new HashMap<>()).get(exception);//查询的异常统计值大于原有值时,表示新发生异常if (lastValue != null && value > lastValue) {String content = String.format(ALARM_TPL, instanceName, exception);alarmMessage.sendData(content);instanceCount.get(instanceName).put(exception, value);} else {Map map = instanceCount.getOrDefault(instanceName, new HashMap<>());map.put(exception, value);instanceCount.put(instanceName, map);}}return Mono.just(0d);}).subscribe();}private Integer getValue(Instance instance, String tags) {String reqUrl = instance.getRegistration().getManagementUrl() + "/metrics/http.server.requests?tag=exception:" + tags;ResponseEntity responseEntity = restTemplate.getForEntity(reqUrl, String.class);String body = responseEntity.getBody();JSONObject bodyObject = JSON.parseObject(body);JSONArray measurementsArray = bodyObject.getJSONArray("measurements");if (measurementsArray != null && !measurementsArray.isEmpty()) {return measurementsArray.getJSONObject(0).getInteger("value");}return 0;}private List getExceptionTag(Instance instance) {try {String reqUrl = instance.getRegistration().getManagementUrl() + "/metrics/http.server.requests";log.debug("check jvm {},uri {}", instance.getRegistration().getName(), reqUrl);ResponseEntity responseEntity = restTemplate.getForEntity(reqUrl, String.class);String body = responseEntity.getBody();JSONObject bodyObject = JSON.parseObject(body);JSONArray tagsArray = bodyObject.getJSONArray("availableTags");if (tagsArray != null && !tagsArray.isEmpty()) {for (Object tag : tagsArray) {JSONObject tagObject = (JSONObject) tag;if ("exception".equals(tagObject.getString("tag"))) {List valuesList = tagObject.getJSONArray("values").toJavaList(String.class);return valuesList.stream().filter(s -> !exclude.contains(s)).collect(Collectors.toList());}}}} catch (Exception ex) {log.error(ex.getMessage());}return Collections.emptyList();}public long getInterval() {return interval;}public void setInterval(long interval) {this.interval = interval;}public String getExclude() {return exclude;}public void setExclude(String exclude) {this.exclude = exclude;}public boolean isEnabled() {return enabled;}public void setEnabled(boolean enabled) {this.enabled = enabled;}public String getExcludeInstances() {return excludeInstances;}public void setExcludeInstances(String excludeInstances) {this.excludeInstances = excludeInstances;}private void start() {this.scheduler = Schedulers.newSingle("exception-check");this.subscription = Flux.interval(Duration.ofSeconds(this.interval)).subscribeOn(this.scheduler).subscribe(this::checkFn);initInstanceCount();}private void initInstanceCount() {repository.findAll().map(instance -> {String instanceName = instance.getRegistration().getName();List exceptionList = getExceptionTag(instance);for (String exception : exceptionList) {Integer value = getValue(instance, exception);Map map = instanceCount.getOrDefault(instanceName, new HashMap<>());map.put(exception, value);instanceCount.put(instanceName, map);}return Mono.just(0d);}).subscribe();}private void stop() {if (this.subscription != null) {this.subscription.dispose();this.subscription = null;}if (this.scheduler != null) {this.scheduler.dispose();this.scheduler = null;}}
}

其中

/*** 排除异常*/
private String exclude = "None,BizException";

该处代码用来排除不告警的异常,因为我们的很多业务异常也会被SBA2记录,此类异常不太具有参考价值,排除。

private void start() {this.scheduler = Schedulers.newSingle("exception-check");this.subscription = Flux.interval(Duration.ofSeconds(this.interval)).subscribeOn(this.scheduler).subscribe(this::checkFn);initInstanceCount();
}private void initInstanceCount() {repository.findAll().map(instance -> {String instanceName = instance.getRegistration().getName();List exceptionList = getExceptionTag(instance);for (String exception : exceptionList) {Integer value = getValue(instance, exception);Map map = instanceCount.getOrDefault(instanceName, new HashMap<>());map.put(exception, value);instanceCount.put(instanceName, map);}return Mono.just(0d);}).subscribe();
}

该处代码用于在SBA2启动的时候重新价值对应服务的异常到内存中,由于SBA2默认都是将异常保存在内存中,每次重启就会丢失。
其他同JVM监控,不再叙述。

相关内容

热门资讯

埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
长白山自助游攻略 吉林长白山游... 昨天介绍了西坡的景点详细请看链接:一个人的旅行,据说能看到长白山天池全凭运气,您的运气如何?今日介绍...
脚上的穴位图 脚面经络图对应的... 人体穴位作用图解大全更清晰直观的标注了各个人体穴位的作用,包括头部穴位图、胸部穴位图、背部穴位图、胳...
猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...
demo什么意思 demo版本... 618快到了,各位的小金库大概也在准备开闸放水了吧。没有小金库的,也该向老婆撒娇卖萌服个软了,一切只...
世界上最漂亮的人 世界上最漂亮... 此前在某网上,选出了全球265万颜值姣好的女性。从这些数量庞大的女性群体中,人们投票选出了心目中最美...
埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
长白山自助游攻略 吉林长白山游... 昨天介绍了西坡的景点详细请看链接:一个人的旅行,据说能看到长白山天池全凭运气,您的运气如何?今日介绍...