This is an automated email from the ASF dual-hosted git repository.

gongchao pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hertzbeat.git


The following commit(s) were added to refs/heads/master by this push:
     new 0699e8934 [Improve] Refactor the notification sending logic. (#2180)
0699e8934 is described below

commit 0699e89346c164a4ee28c71d3c4b58ed2e87f4c9
Author: crossoverJie <[email protected]>
AuthorDate: Thu Jul 4 10:21:01 2024 +0800

    [Improve] Refactor the notification sending logic. (#2180)
    
    Co-authored-by: tomsun28 <[email protected]>
---
 .../apache/hertzbeat/alert/AlerterWorkerPool.java  | 31 ++++++++++++
 .../manager/component/alerter/DispatcherAlarm.java | 56 ++++++++++++----------
 .../impl/AbstractAlertNotifyHandlerImpl.java       |  7 ---
 .../manager/service/impl/MailServiceImpl.java      |  6 ---
 4 files changed, 61 insertions(+), 39 deletions(-)

diff --git 
a/alerter/src/main/java/org/apache/hertzbeat/alert/AlerterWorkerPool.java 
b/alerter/src/main/java/org/apache/hertzbeat/alert/AlerterWorkerPool.java
index a8ebf4a1f..78afb1457 100644
--- a/alerter/src/main/java/org/apache/hertzbeat/alert/AlerterWorkerPool.java
+++ b/alerter/src/main/java/org/apache/hertzbeat/alert/AlerterWorkerPool.java
@@ -34,9 +34,11 @@ import org.springframework.stereotype.Component;
 public class AlerterWorkerPool {
 
     private ThreadPoolExecutor workerExecutor;
+    private ThreadPoolExecutor notifyExecutor;
 
     public AlerterWorkerPool() {
         initWorkExecutor();
+        initNotifyExecutor();
     }
 
     private void initWorkExecutor() {
@@ -57,6 +59,24 @@ public class AlerterWorkerPool {
                 new ThreadPoolExecutor.AbortPolicy());
     }
 
+    private void initNotifyExecutor() {
+        ThreadFactory threadFactory = new ThreadFactoryBuilder()
+                .setUncaughtExceptionHandler((thread, throwable) -> {
+                    log.error("notifyExecutor has uncaughtException.");
+                    log.error(throwable.getMessage(), throwable);
+                })
+                .setDaemon(true)
+                .setNameFormat("notify-worker-%d")
+                .build();
+        notifyExecutor = new ThreadPoolExecutor(6,
+                10,
+                10,
+                TimeUnit.SECONDS,
+                new SynchronousQueue<>(),
+                threadFactory,
+                new ThreadPoolExecutor.AbortPolicy());
+    }
+
     /**
      * Run the alerter task
      * @param runnable task
@@ -65,4 +85,15 @@ public class AlerterWorkerPool {
     public void executeJob(Runnable runnable) throws 
RejectedExecutionException {
         workerExecutor.execute(runnable);
     }
+
+    /**
+     * Executes the given runnable task using the notifyExecutor.
+     *
+     * @param runnable the task to be executed
+     * @throws RejectedExecutionException if the task cannot be accepted for 
execution
+     */
+    public void executeNotify(Runnable runnable) throws 
RejectedExecutionException {
+        notifyExecutor.execute(runnable);
+    }
+
 }
diff --git 
a/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/DispatcherAlarm.java
 
b/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/DispatcherAlarm.java
index a192bf34f..f9cee2a5d 100644
--- 
a/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/DispatcherAlarm.java
+++ 
b/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/DispatcherAlarm.java
@@ -20,6 +20,7 @@ package org.apache.hertzbeat.manager.component.alerter;
 import com.google.common.collect.Maps;
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 import java.util.ServiceLoader;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.hertzbeat.alert.AlerterWorkerPool;
@@ -85,7 +86,15 @@ public class DispatcherAlarm implements InitializingBean {
         }
         byte type = receiver.getType();
         if (alertNotifyHandlerMap.containsKey(type)) {
-            alertNotifyHandlerMap.get(type).send(receiver, noticeTemplate, 
alert);
+            AlertNotifyHandler alertNotifyHandler = 
alertNotifyHandlerMap.get(type);
+            if (noticeTemplate == null) {
+                noticeTemplate = 
noticeConfigService.getDefaultNoticeTemplateByType(alertNotifyHandler.type());
+            }
+            if (noticeTemplate == null) {
+                log.error("alert does not have mapping default notice 
template. type: {}.", alertNotifyHandler.type());
+                throw new NullPointerException(alertNotifyHandler.type() + " 
does not have mapping default notice template");
+            }
+            alertNotifyHandler.send(receiver, noticeTemplate, alert);
             return true;
         }
         return false;
@@ -96,11 +105,14 @@ public class DispatcherAlarm implements InitializingBean {
     }
 
     private NoticeTemplate getOneTemplateById(Long id) {
+        if (id == null) {
+            return null;
+        }
         return noticeConfigService.getOneTemplateById(id);
     }
 
-    private List<NoticeRule> matchNoticeRulesByAlert(Alert alert) {
-        return noticeConfigService.getReceiverFilterRule(alert);
+    private Optional<List<NoticeRule>> matchNoticeRulesByAlert(Alert alert) {
+        return 
Optional.ofNullable(noticeConfigService.getReceiverFilterRule(alert));
     }
 
     private class DispatchTask implements Runnable {
@@ -131,29 +143,21 @@ public class DispatcherAlarm implements InitializingBean {
         }
 
         private void sendNotify(Alert alert) {
-            List<NoticeRule> noticeRules = matchNoticeRulesByAlert(alert);
-            // todo Send notification here temporarily single thread
-            if (noticeRules != null) {
-                for (NoticeRule rule : noticeRules) {
-                    try {
-                        if (rule.getTemplateId() == null) {
-                            List<Long> receiverIdList = rule.getReceiverId();
-                            for (Long receiverId : receiverIdList) {
-                                sendNoticeMsg(getOneReceiverById(receiverId),
-                                        null, alert);
-                            }
-                        } else {
-                            List<Long> receiverIdList = rule.getReceiverId();
-                            for (Long receiverId : receiverIdList) {
-                                sendNoticeMsg(getOneReceiverById(receiverId),
-                                    getOneTemplateById(rule.getTemplateId()), 
alert);
-                            }
-                        }
-                    } catch (AlertNoticeException e) {
-                        log.warn("DispatchTask sendNoticeMsg error, message: 
{}", e.getMessage());
-                    }
-                }
-            }
+            matchNoticeRulesByAlert(alert).ifPresent(noticeRules -> {
+                noticeRules.forEach(rule -> {
+                    workerPool.executeNotify(() -> {
+                        rule.getReceiverId()
+                                .forEach(receiverId -> {
+                                    try {
+                                        
sendNoticeMsg(getOneReceiverById(receiverId),
+                                                
getOneTemplateById(rule.getTemplateId()), alert);
+                                    } catch (AlertNoticeException e) {
+                                        log.warn("DispatchTask sendNoticeMsg 
error, message: {}", e.getMessage());
+                                    }
+                                });
+                    });
+                });
+            });
         }
     }
 
diff --git 
a/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AbstractAlertNotifyHandlerImpl.java
 
b/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AbstractAlertNotifyHandlerImpl.java
index 0b8d44aef..43f9b88de 100644
--- 
a/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AbstractAlertNotifyHandlerImpl.java
+++ 
b/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AbstractAlertNotifyHandlerImpl.java
@@ -107,13 +107,6 @@ abstract class AbstractAlertNotifyHandlerImpl implements 
AlertNotifyHandler {
         model.put("content", alert.getContent());
         model.put("tagsLabel", bundle.getString("alerter.notify.tags"));
         model.put("tags", alert.getTags());
-        if (noticeTemplate == null) {
-            noticeTemplate = 
noticeConfigService.getDefaultNoticeTemplateByType(type());
-        }
-        if (noticeTemplate == null) {
-            log.error("alert does not have mapping default notice template. 
type: {}.", type());
-            throw new NullPointerException(type() + " does not have mapping 
default notice template");
-        }
         // Single instance reuse cache considers mulitple-threading issues
         String templateName = "freeMakerTemplate";
         stringLoader.putTemplate(templateName, noticeTemplate.getContent());
diff --git 
a/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/MailServiceImpl.java
 
b/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/MailServiceImpl.java
index 77baadda4..4e91ea73d 100644
--- 
a/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/MailServiceImpl.java
+++ 
b/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/MailServiceImpl.java
@@ -95,12 +95,6 @@ public class MailServiceImpl implements MailService {
         model.put("consoleUrl", alerterProperties.getConsoleUrl());
         model.put("nameContent", bundle.getString("alerter.notify.content"));
         model.put("content", alert.getContent());
-        if (noticeTemplate == null) {
-            noticeTemplate = 
noticeConfigService.getDefaultNoticeTemplateByType((byte) 1);
-        }
-        if (noticeTemplate == null) {
-            throw new NullPointerException("email does not have mapping 
default notice template");
-        }
         StringTemplateLoader stringLoader = new StringTemplateLoader();
         String templateName = "mailTemplate";
         stringLoader.putTemplate(templateName, noticeTemplate.getContent());


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to