Hello Word
一个简单的例子
MyConsumers.java
package com.example.demo12;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class MyConsumers {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory=new ConnectionFactory();
factory.setPort(30672);//k8s映射出的端口对应 5672端口
factory.setHost("192.168.1.171");
factory.setUsername("admin");
factory.setPassword("admin");
factory.setVirtualHost("/text01");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
/**
* Declare a queue
* @see com.rabbitmq.client.AMQP.Queue.Declare
* @see com.rabbitmq.client.AMQP.Queue.DeclareOk
* @param queue the name of the queue
* @param durable true if we are declaring a durable queue (the queue will survive a server restart)
* @param exclusive true if we are declaring an exclusive queue (restricted to this connection)
* @param autoDelete true if we are declaring an autodelete queue (server will delete it when no longer in use)
* @param arguments other properties (construction arguments) for the queue
* @return a declaration-confirm method to indicate the queue was successfully declared
* @throws java.io.IOException if an error is encountered
*/
channel.queueDeclare("helloWorld",false,false,false,null);
channel.basicConsume("helloWorld", false, new Reciver(channel));
}
static class Reciver extends DefaultConsumer{
Channel channel;
public Reciver(Channel channel) {
super(channel);
this.channel=channel;
}
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//super.handleDelivery(consumerTag, envelope, properties, body);
System.out.println(new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);
}
}
}MyProducer.java
package com.example.demo12;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class MyProducer {
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
ConnectionFactory factory=new ConnectionFactory();
factory.setPort(30672);
factory.setHost("192.168.1.171");
factory.setUsername("admin");
factory.setPassword("admin");
factory.setVirtualHost("/text01");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("helloWorld",false,false,false,null);
String meg="Hello World";
Thread.sleep(3000);
for (int i=0;i<100000;i++){
channel.basicPublish("","helloWorld",null,(meg+i).getBytes());
}
channel.close();;
connection.close();
}
}本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!