MQTT消息环境搭建与java客户端demo

1..下载安装包

http://mosquitto.org/download/    以版本1.5为例,下载mosquitto-1.5.tar.gz

2.下载依赖环境

yum -y install gcc gcc-c++ openssl-devel c-ares-devel  wget cmake

yum install -y c-ares-devel e2fsprogs-devel uuid-devel libuuid-devel

3.解压mosquitto-1.5进入目录编译与安装

make && make install

4.修改配置文件

    设置用户为root

  允许匿名

  设置服务端口与监听消息端口

5.把新共享库目录加入到共享库配置文件中

   cat /etc/ld.so.conf

   echo  "/usr/local/lib" >> /etc/ld.so.conf

   ldconfig

6.启动服务

  mosquitto -c /etc/mosquitto/mosquitto.conf -d                       (-d表示后台启动)

7.启动消费者例子

  mosquitto_sub -t rulee

8.发送消息

  mosquitto_pub -h localhost -p 9090 -t rulee -m "hello rule engine"        (-h 服务器地址  -p监听端口)

9.检查消费者中是否有显示"hello rule engine"

 

MQTT的java api

 

pom

<dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    <version>1.2.0</version>
</dependency>

 

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MQTTUtil {

    private static MqttClient client;   //Mqtt客户端
    private static int qos = 1;         //数据服务质量

    /**
     * 初始化连接
     *
     * @param broker   mqtt节点
     * @param userName 用户名
     * @param password 密码
     * @param clientId 客户端id
     * @throws MqttException
     */
    public static void initMqttClient(String broker, String userName, String password, String clientId) throws MqttException {
        MemoryPersistence persistence = new MemoryPersistence();// 内存存储
        client = new MqttClient(broker, clientId, persistence);// 创建客户端
        MqttConnectOptions connOpts = new MqttConnectOptions();// 创建链接参数
        connOpts.setCleanSession(false);    // 在重新启动和重新连接时记住状态
        connOpts.setUserName(userName);     // 设置连接的用户名
        connOpts.setPassword(password.toCharArray());
        connOpts.setConnectionTimeout(10);  // 设置超时时间 单位为秒
        connOpts.setKeepAliveInterval(20);  // 设置会话心跳时间,客户端发送个消息判断客户端是否在线,没有重连的机制
        client.connect(connOpts);     // 建立连接
    }

    /**
     * 传入消息
     *
     * @param topic   主题
     * @param message 消息
     * @throws MqttException
     */
    public static void setMessage(String topic, String message) throws MqttException {
        MqttMessage data = new MqttMessage(message.getBytes());// 创建消息
        data.setQos(qos); // 设置消息的服务质量
        client.publish(topic, data);// 发布消息
    }

    /**
     * 消费的数据处理方式
     */
    public static void setCallback() {
        client.setCallback(new MqttCallback() {
            public void connectionLost(Throwable cause) {
                System.out.println("断开连接");
            }

            public void messageArrived(String topic, MqttMessage message) throws Exception {
                //"topic:"  topic,"Qos:" + message.getQos()
                System.out.println("接收" + new String(message.getPayload()));//消息
            }

            public void deliveryComplete(IMqttDeliveryToken token) {
                //token.isComplete()
                System.out.println("完成");
            }
        });
    }

    /**
     * @param topic
     * @throws MqttException
     */
    public static void getMessage(String topic) throws MqttException {
        client.subscribe(topic, qos);//订阅消息
    }

    public static void close() throws MqttException {
        client.disconnect();// 断开连接
        client.close();// 关闭客户端
    }

    /**
     * 异常信息打印
     *
     * @param me
     */
    public static void error(MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }

    /**
     * 测试类
     * @param args
     */
    public static void main(String[] args) {
        try {
            initMqttClient("tcp://yc3:1883", "test", "test", "pubClient");初始化客户端
            setCallback();//设置回调函数
            getMessage("rulee");//订阅
            for (int i = 0; i < 10; i++) {//发布
                setMessage("rulee", "12312312");
            }
            close();
        } catch (MqttException e) {
            error(e);
        }
    }
}

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的Java代码示例,演示如何在MQTT服务上将消息从一个客户转发到另一个客户。 ```java import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; public class MqttServer { private static final String BROKER_URL = "tcp://localhost:1883"; private static final String CLIENT_ID = "server"; private static final String TOPIC = "test"; private static final int QOS = 1; public static void main(String[] args) throws MqttException { // 创建 MQTT 客户 MqttClient mqttClient = new MqttClient(BROKER_URL, CLIENT_ID, new MemoryPersistence()); // 创建消息转发器 mqttClient.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable throwable) { System.out.println("连接丢失"); } @Override public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception { // 接收到消息时转发给另一个客户 String payload = new String(mqttMessage.getPayload()); String newTopic = "another_client/topic"; mqttClient.publish(newTopic, new MqttMessage(payload.getBytes())); } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { System.out.println("消息投递完成"); } }); // 连接 MQTT 服务 MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(true); mqttClient.connect(options); mqttClient.subscribe(TOPIC, QOS); // 循环等待消息 while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 在上面的代码中,我们创建了一个名为 `MqttServer` 的类作为 MQTT 服务。在 `main()` 方法中,我们首先创建了一个 MQTT 客户,并设置了一个消息转发器,用于接收从一个客户发布的消息,并将其转发给另一个客户。 在转发器的 `messageArrived()` 方法中,我们将接收到的消息的负载提取出来,并使用 `mqttClient.publish()` 方法将其发布到另一个客户的主题上。 最后,在循环中我们使用 `Thread.sleep()` 方法等待消息的到来。你可以将 `MqttServer` 类部署到你的 MQTT 服务器上,并在另一个客户上订阅 `another_client/topic` 主题来接收转发的消息

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小钻风巡山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值