package com.moyi.controlplane.usage; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class OpsNotificationService { private final JdbcTemplate jdbc;private final Environment env; public OpsNotificationService(JdbcTemplate jdbc,Environment env) {this.jdbc=jdbc;this.env=env;} private String value(String name) {return env.getProperty(name,"").strip();} public boolean available() {return !value("MOYI_SMTP_HOST").isEmpty()&&!value("MOYI_SMTP_FROM").isEmpty();} @Scheduled(fixedDelayString="${moyi.ops.notification-interval-ms:60000}") @Transactional public void deliver() { if(!available()) return; var rows=jdbc.queryForList("SELECT * FROM ops_alert_events WHERE notification_status IN ('pending','retry') AND notification_attempts<3 AND (notification_next_at IS NULL OR notification_next_at<=now()) ORDER BY created_at LIMIT 5 FOR UPDATE SKIP LOCKED"); for(var row:rows) { try { var mail=new JavaMailSenderImpl();mail.setHost(value("MOYI_SMTP_HOST"));mail.setPort(env.getProperty("MOYI_SMTP_PORT",Integer.class,465));mail.setUsername(value("MOYI_SMTP_USERNAME"));mail.setPassword(env.getProperty("MOYI_SMTP_PASSWORD",""));mail.setDefaultEncoding("UTF-8"); var p=mail.getJavaMailProperties();p.setProperty("mail.smtp.auth",String.valueOf(!value("MOYI_SMTP_USERNAME").isEmpty()));p.setProperty("mail.smtp.ssl.enable",env.getProperty("MOYI_SMTP_SSL","true"));p.setProperty("mail.smtp.starttls.enable",env.getProperty("MOYI_SMTP_STARTTLS","false"));p.setProperty("mail.smtp.starttls.required",env.getProperty("MOYI_SMTP_STARTTLS","false"));p.setProperty("mail.smtp.ssl.checkserveridentity","true"); for(String name:new String[]{"connectiontimeout","timeout","writetimeout"}) p.setProperty("mail.smtp."+name,"5000"); var message=new SimpleMailMessage();message.setFrom(value("MOYI_SMTP_FROM"));message.setTo(row.get("notification_email").toString());message.setSubject("MOYI 网关错误率告警");message.setText("告警编号:"+row.get("id")+"\n失败请求:"+row.get("failed_requests")+" / "+row.get("total_requests")+"\n错误率:"+row.get("error_percent")+"%\n请登录管理端的渠道健康与告警查看详情。");mail.send(message); jdbc.update("UPDATE ops_alert_events SET notification_status='sent',notification_attempts=notification_attempts+1 WHERE id=?",row.get("id")); } catch(Exception ignored) {jdbc.update("UPDATE ops_alert_events SET notification_status=CASE WHEN notification_attempts>=2 THEN 'failed' ELSE 'retry' END,notification_attempts=notification_attempts+1,notification_next_at=now()+interval '10 minutes' WHERE id=?",row.get("id"));} } } }