本文共 3238 字,大约阅读时间需要 10 分钟。
RabbitMQ是一种消息中间件,它接收和转发消息,可以理解为邮局。只是RabbitMQ接收,处理,转发的是二进制的数据,邮局处理的一般为纸。
brew install rabbitmq
cat << EOF > /etc/yum.repos.d/rabbit.repo[rabbitmq-erlang]name=rabbitmq-erlangbaseurl=https://dl.bintray.com/rabbitmq/rpm/erlang/21/el/7gpgcheck=1gpgkey=https://dl.bintray.com/rabbitmq/Keys/rabbitmq-release-signing-key.ascrepo_gpgcheck=0enabled=1EOFyum install rabbitmq-server
rabbitmq-server
ch.qos.logback logback-classic 1.2.3 com.rabbitmq amqp-client 4.2.0
/** * @author aihe 2018/9/6 */public class Producer { private final static String QUEUE_NAME = "hello1"; public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("127.0.0.1"); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello World"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println("发送消息:" + message); try { channel.close(); connection.close(); } catch (TimeoutException e) { e.printStackTrace(); } }}
channel.queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
生产和消费消息都是通过channel的。channel指定具体为那个queue
/** * @author aihe 2018/9/6 */public class Consumer { private final static String QUEUE_NAME = "hello1"; public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] 正在等待消息. 退出按 CTRL+C"); com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" 接收消息:'" + message + "'"); } }; channel.basicConsume(QUEUE_NAME, true, consumer); }}
生产者
消费者
// 查看有哪些插件rabbitmq-plugins list// 启用管理界面rabbitmq-plugins enable rabbitmq_management
进入管理界面
进入地址:http://127.0.0.1:15672/ 账号和密码:guest guest这些参数大部分都是可以从rabbitmqctl命令获得的。
学习下消息中间件
转载地址:http://axpmx.baihongyu.com/