Java+MySQL实现消息推送 构建一个支持多种模板的通知中心
·

消息推送系统架构设计
构建基于Java和MySQL的通知中心需采用分层设计,包括数据层、业务逻辑层和推送层。数据层负责模板存储和消息队列管理,业务逻辑层处理模板渲染和消息分发,推送层对接邮件、短信等第三方服务。
数据库表结构设计
通知模板表(notification_template)
CREATE TABLE notification_template (
id INT PRIMARY KEY AUTO_INCREMENT,
template_code VARCHAR(50) UNIQUE,
title_template TEXT,
content_template TEXT,
channel_type ENUM('EMAIL','SMS','APP_PUSH'),
status TINYINT DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
用户消息表(user_message)
CREATE TABLE user_message (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_id VARCHAR(36),
template_code VARCHAR(50),
title VARCHAR(255),
content TEXT,
channel_type ENUM('EMAIL','SMS','APP_PUSH'),
status ENUM('PENDING','SENT','FAILED'),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_user_status (user_id, status)
);
模板引擎实现
使用Velocity进行动态模板渲染:
public class TemplateRenderer {
private VelocityEngine velocityEngine;
public String render(String template, Map<String, Object> params) {
VelocityContext context = new VelocityContext(params);
StringWriter writer = new StringWriter();
velocityEngine.evaluate(context, writer, "template", template);
return writer.toString();
}
}
消息队列处理
采用Spring JMS与ActiveMQ集成实现异步处理:
@Component
public class MessageQueueConsumer {
@JmsListener(destination = "notification.queue")
public void processMessage(NotificationDTO notification) {
// 调用推送服务发送消息
pushService.send(notification);
}
}
多通道推送集成
构建统一推送接口:
public interface PushChannel {
boolean send(NotificationMessage message);
}
@Service
public class EmailPushChannel implements PushChannel {
@Override
public boolean send(NotificationMessage message) {
// 实现邮件发送逻辑
}
}
@Service
public class SmsPushChannel implements PushChannel {
@Override
public boolean send(NotificationMessage message) {
// 实现短信发送逻辑
}
}
模板管理API
提供RESTful接口管理模板:
@RestController
@RequestMapping("/api/templates")
public class TemplateController {
@PostMapping
public Response createTemplate(@RequestBody TemplateDTO dto) {
// 模板创建逻辑
}
@GetMapping("/{code}")
public TemplateDTO getTemplate(@PathVariable String code) {
// 模板查询逻辑
}
}
消息发送服务
封装消息发送入口:
@Service
public class NotificationService {
public void sendNotification(String templateCode,
String userId,
Map<String, Object> params) {
// 获取模板
Template template = templateRepository.findByCode(templateCode);
// 渲染内容
String title = templateRenderer.render(template.getTitleTemplate(), params);
String content = templateRenderer.render(template.getContentTemplate(), params);
// 持久化消息
UserMessage message = new UserMessage(userId, templateCode,
title, content, template.getChannelType());
messageRepository.save(message);
// 加入消息队列
jmsTemplate.convertAndSend("notification.queue", message);
}
}
性能优化方案
采用分表策略处理海量消息数据,按用户ID哈希分表。对高频模板使用本地缓存,通过Caffeine实现:
@Configuration
public class CacheConfig {
@Bean
public Cache<String, Template> templateCache() {
return Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(1, TimeUnit.HOURS)
.build();
}
}
监控与报警
集成Prometheus监控关键指标:
@Bean
public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config().commonTags(
"application", "notification-center"
);
}
安全控制
实现模板权限校验:
@Aspect
@Component
public class TemplateAccessAspect {
@Before("@annotation(RequireTemplatePermission)")
public void checkPermission(JoinPoint jp) {
// 权限验证逻辑
}
}
该方案通过模块化设计实现高扩展性,支持快速接入新的推送渠道。采用消息队列解耦发送流程,确保系统在高并发场景下的可靠性。模板引擎与业务逻辑分离,便于维护多种消息模板。
更多推荐
所有评论(0)