SpringBoot+mqtt + ActiveMq + mqttws31.js 实现后台向前台推送消息

SpringBoot版本:1.4.4.RELEASE

ActiveMq版本:5.15.4

后台代码:

pom文件除常规配置外加入:


     org.springframework.integration
     spring-integration-mqtt

加入配置类:

import java.util.Random;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
public class MqttConfiguration {

	private Random rand = new Random();

	private String clientId = "";

	// ==================== 连接activemq ====================
	@Bean
	public MqttPahoClientFactory clientFactory() {
		DefaultMqttPahoClientFactory clientFactory = new DefaultMqttPahoClientFactory();
		clientFactory.setServerURIs("tcp://localhost:1883");
		clientFactory.setUserName("system");
		clientFactory.setPassword("manager");
		return clientFactory;
	}

	// ==================== 生产者 ====================
	@Bean
	public MessageChannel mqttOutboundChannel() {
		return new DirectChannel();
	}

	@Bean
	@ServiceActivator(inputChannel = "mqttOutboundChannel") // 绑定生产者
	public MqttPahoMessageHandler mqttOutbound(MqttPahoClientFactory clientFactory) {
		MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
				clientId + String.format("%05d", rand.nextInt(10000)), clientFactory);
		messageHandler.setAsync(true);
		messageHandler.setDefaultQos(1);
		messageHandler.setDefaultRetained(false);
		messageHandler.setAsyncEvents(false);
		return messageHandler;
	}

	// ==================== 消费者 ====================
	@Bean
	public MessageChannel mqttInputChannel() {
		return new DirectChannel();
	}

	@Bean
	@ServiceActivator(inputChannel = "mqttInputChannel") // 绑定消费者
	public MessageHandler handler() {
		return new ReceiveMessageHandler();
	}

	@Bean
	public MessageProducerSupport mqttInbound() {
		MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
				clientId + String.format("%05d", rand.nextInt(10000)), clientFactory(), "mqtt-topic-demo");
		adapter.setConverter(new DefaultPahoMessageConverter());
		adapter.setQos(1);
		adapter.setOutputChannel(mqttInputChannel());
		return adapter;
	}

}

后台消费者:

import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import ch.qos.logback.classic.Logger;

public class ReceiveMessageHandler implements MessageHandler {

	protected static Logger logger = (Logger) LoggerFactory.getLogger(ReceiveMessageHandler.class);

	@Override
	public void handleMessage(Message message) throws MessagingException {
		String str = (String) message.getPayload();
		System.out.println("接收到消息:" + str);
	}
}

消息发送接口:

import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.messaging.Message;

/**
 * 消息发送接口,不需要实现,spring会通过代理的方式实现
 */
@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttMessageGateway {
	void sendMessage(Message message);
}

发送消息业务类:

@Autowired
private MqttMessageGateway gateway;
Message message = MessageBuilder.withPayload("修改笔记,新的笔记名称:" + oldSysNote.getNoteName())
			  .setHeader(MqttHeaders.TOPIC, "mqtt-topic-demo").build();
gateway.sendMessage(message);

前端代码:

引入js:

mqttws31.min.js

编写连接代码:
client = new Paho.MQTT.Client("localhost", 61614, "" ,"web" + RndNum(12)); //建立客户端实例
client.connect({
	onSuccess: onConnect,
	userName: "system",
	password: "manager"
}); //连接服务器并注册连接成功处理事件
client.onConnectionLost = onConnectionLost; //注册连接断开处理事件
client.onMessageArrived = onMessageArrived; //注册消息接收处理事件
function onConnect() {
	client.subscribe("mqtt-topic-demo"); //订阅主题
}
function onConnectionLost(responseObject) {
	if(responseObject.errorCode !== 0) {
		console.log("连接已断开");
	}
}
function onMessageArrived(message) {
	var ss = message.destinationName;
	var meg = message.payloadString;
	alert("您有新消息:" + meg);
}

启动ActiveMq服务器:

这里使用windows版本:

启动服务后访问控制台,可以看到主题

SpringBoot+mqtt + ActiveMq + mqttws31.js 实现后台向前台推送消息_第1张图片

效果:

当修改笔记时,推送消息

SpringBoot+mqtt + ActiveMq + mqttws31.js 实现后台向前台推送消息_第2张图片





你可能感兴趣的:(java)