Android接收RabbitMQ消息。


參考:https://blog.csdn.net/qq_36576738/article/details/83754621

我這android這邊就不實現發布消息功能。因為我是在服務端那邊推送消息。

開發工具android studio。

1》建好項目后添加包(目前最新的是5.7.0):

dependencies {
    implementation 'com.rabbitmq:amqp-client:5.7.0'
}

2》在主頁面上加個TextView,用來顯示服務端推送的消息。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtrabbitmqt"
        android:text="rabbitmq"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

3》連接服務器上的RabbitMq:

   /**
     * 連接設置
     */
    private void setupConnectionFactory() {
        factory =  new ConnectionFactory();
        factory.setHost("服務器ip");
        factory.setPort(rabbitmq端口,默認5672);
        factory.setUsername("自己連接rabbitmq賬號");
        factory.setPassword("自己連接rabbitmq的密碼");
    }

 

4》編寫訂閱代碼:

    /**
     * 收消息(從發布者那邊訂閱消息)
     */
    private void basicConsume(final Handler handler){

        try {
            //連接
            Connection connection = factory.newConnection() ;
            //通道
            final Channel channel = connection.createChannel() ;
            //實現Consumer的最簡單方法是將便捷類DefaultConsumer子類化。可以在basicConsume 調用上傳遞此子類的對象以設置訂閱:
            channel.basicConsume("myqueue" , false ,  new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);

                    String msg = new String(body) ;
                    long deliveryTag = envelope.getDeliveryTag() ;
                    channel.basicAck(deliveryTag , false);
                    //從message池中獲取msg對象更高效
                    Message uimsg = handler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", msg);
                    uimsg.setData(bundle);
                    handler.sendMessage(uimsg);

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

整個demo代碼:

package com.ldb.longdb.rabbitmqapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class MainActivity extends AppCompatActivity {

    ConnectionFactory factory;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //連接設置
        setupConnectionFactory();
        //用於從線程中獲取數據,更新ui
        final Handler incomingMessageHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String message = msg.getData().getString("msg");
                TextView tv = (TextView) findViewById(R.id.txtrabbitmqt);
                tv.append(message + '\n');
                Log.i("test", "msg:" + message);
            }
        };
        //開啟消費者線程
        //subscribe(incomingMessageHandler);
        new Thread(new Runnable() {
            @Override
            public void run() {
                basicConsume(incomingMessageHandler);
            }
        }).start();
    }

    /**
     * 連接設置
     */
    private void setupConnectionFactory() {
        factory =  new ConnectionFactory();
        factory.setHost(服務器ip);
        factory.setPort(5672);
        factory.setUsername("longdb");
        factory.setPassword("***");
    }

    /**
     * 收消息(從發布者那邊訂閱消息)
     */
    private void basicConsume(final Handler handler){

        try {
            //連接
            Connection connection = factory.newConnection() ;
            //通道
            final Channel channel = connection.createChannel() ;
            //實現Consumer的最簡單方法是將便捷類DefaultConsumer子類化。可以在basicConsume 調用上傳遞此子類的對象以設置訂閱:
            channel.basicConsume("myqueue" , false ,  new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);

                    String msg = new String(body) ;
                    long deliveryTag = envelope.getDeliveryTag() ;
                    channel.basicAck(deliveryTag , false);
                    //從message池中獲取msg對象更高效
                    Message uimsg = handler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", msg);
                    uimsg.setData(bundle);
                    handler.sendMessage(uimsg);

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
View Code

我是直接打包,然后自己手機安裝測試。

測試步驟:1》app打開

                  2》springcloud服務(springcloud怎樣發布消息,請看上一篇)運行,發送請求。

測試截圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM