最近再写一个项目,怕以后忘记特此留记,不喜勿喷,大神请留言指点。要求:
实时向前端发送消息,运用ActiveMQ
实际应用,在SpringCloud中新建了一个工程作为消息中心,这里不做过多展示;新建一个类
package net.chunxiao.zhmsg.config;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;
import javax.jms.*;
import java.util.Date;
@Component
public class ActiveManager {
@Autowired
JmsMessagingTemplate jmsMessagingTemplate;
/**
* @param data
* @desc 即时发送
*/
public void send(Destination destination,String data) {
this.jmsMessagingTemplate.convertAndSend(destination, data);
}
/**
* @desc 延时发送
*/
public void delaySend(String text, String topicName, Date presentTime, Long sendTime) {
Long time = sendTime-presentTime.getTime();
if(time<=0){
time=0L;
}
//获取连接工厂
ConnectionFactory connectionFactory = this.jmsMessagingTemplate.getConnectionFactory();
try {
//获取连接
Connection connection = connectionFactory.createConnection();
connection.start();
//获取session
Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建一个消息队列
Destination destination = session.createTopic(topicName);
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
TextMessage message = session.createTextMessage(text);
//设置延迟时间
message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
//发送
producer.send(message);
session.commit();
producer.close();
session.close();
connection.close();
} catch (Exception e) {
e.getMessage();
}
}
}
以上为完整类的代码
使用方式
@Autowired
private ActiveManager activeManager;
//将实体类转换成json字符串
private Gson gson = new Gson();
activeManager.delaySend (jsonString, "topic" + '此地为用户ID', date,
mmsMainVO.getSendTime())