标签:sage intern private art and eth ica rac 实现
引入
implementation ‘com.rabbitmq:amqp-client:5.7.0‘
指定jdk版本,在build.grald app目录下
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
网络
<uses-permission android:name="android.permission.INTERNET"/>
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.os.Message; 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(""); 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 | TimeoutException e) { e.printStackTrace(); } } }
标签:sage intern private art and eth ica rac 实现
原文地址:https://www.cnblogs.com/inthecloud/p/11880000.html