rabbitmq学习(java客户端)

来源:互联网 发布:深圳中科软件 编辑:程序博客网 时间:2024/06/06 05:34

1、rabbitmq采取的是集群安装

2、项目为maven工程,只需要在pom文件中加入:

<dependencies>    <dependency>            <groupId>com.rabbitmq</groupId>            <artifactId>amqp-client</artifactId>            <version>3.6.1</version>    </dependency></dependencies>

3.源码

(一):Send.class

import com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import com.rabbitmq.client.ConnectionFactory;/** * Created by joyce on 2017/11/13. */public class Send {    private final static String QUEUE_NAME = "test";    public static void main(String[] args) throws Exception {        ConnectionFactory factory = new ConnectionFactory();        factory.setHost("集群中的ip");
        factory.setUsername("usrname");        factory.setPassword("passwd");        Connection connection = factory.newConnection();        Channel channel = connection.createChannel();        channel.queueDeclare(QUEUE_NAME, false, false, false, null);        String message = "Hello World! zyy";        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));        System.out.println(" [x] Sent '" + message + "'");        channel.close();        connection.close();    }}

(二):Recv.class

import com.rabbitmq.client.*;import java.io.IOException;/** * Created by joyce on 2017/11/13. */public class Recv {    private final static String QUEUE_NAME = "test";    public static void main(String[] args) throws  Exception {        ConnectionFactory factory = new ConnectionFactory();        factory.setHost("IP");        factory.setUsername("usrname");        factory.setPassword("passwd");        Connection connection = factory.newConnection();        Channel channel = connection.createChannel();        channel.queueDeclare(QUEUE_NAME, false, false, false, null);        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(" [x] Received '" + message + "'");            }        };        channel.basicConsume(QUEUE_NAME, true, consumer);    }}

(三):直接跑main(),可以在控制台看见输出...
                               看到我请叫我去写作业_(wechat:jshasmith0826)

原创粉丝点击