@Component
public class MsgPubMqttUtil {
@Resource
private EmqClient emqClient;
@Resource
private MqttProperties mqttProperties;
@Resource
private TMessageTemplateMapper tMessageTemplateMapper;
@Resource
private TMessageMapper tMessageMapper;
private static MsgPubMqttUtil msgPubMqttUtil;
@PostConstruct
public void init(){
msgPubMqttUtil = this;
msgPubMqttUtil.emqClient = this.emqClient;
msgPubMqttUtil.mqttProperties = this.mqttProperties;
msgPubMqttUtil.tMessageTemplateMapper = this.tMessageTemplateMapper;
msgPubMqttUtil.tMessageMapper = this.tMessageMapper;
}
/**
* 发送消息
* templateId 模板id
* pubId 订阅者id
* userType 订阅者用户类型
* @throws Exception
*/
public void sendMqttMessage(String templateId, String pubId, String userType) {
// 连接服务器端
emqClient.connect(mqttProperties.getUsername(),mqttProperties.getPassword());
// 拼接消息主题
StringBuffer result = new StringBuffer();
result.append("testtopic");
result.append("/");
result.append(pubId);
// 获取消息模板
TMessageTemplate tMessageTemplate = msgPubMqttUtil.tMessageTemplateMapper.selectById(templateId);
Map<String,String> map = new HashMap<String,String>();
map.put("msgTemplateTitle",tMessageTemplate.getMsgTemplateTitle());
map.put("templateContent",tMessageTemplate.getTemplateContent());
String str = ConverUitl.getMapToString(map);
// 发布消息
emqClient.publish(result.toString(), str, QosEnum.QoS2,false);
// 存入历史记录表
TMessage tMessage = new TMessage();
tMessage.setId(SnowflakeIdWorkerUtil.nextId());
tMessage.setCreated(new Date());
tMessage.setUpdated(new Date());
tMessage.setReadStatus("1"); // 设置为未读
tMessage.setMsgTitle(map.get("msgTemplateTitle"));
tMessage.setMsgContent(map.get("templateContent"));
tMessage.setUserType(userType); // 接收者类型
tMessage.setUserId(pubId); // 接收者主键
tMessage.setMtId(templateId); // 关联的模板id
tMessageMapper.insert(tMessage);
}
}