博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用rabbitMQ实现生产者消费者
阅读量:6872 次
发布时间:2019-06-26

本文共 1955 字,大约阅读时间需要 6 分钟。

hot3.png

利用RabbitMQ实现生产者和消费者的一个小Demo

不做讲解 直接上代码

import com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import com.rabbitmq.client.ConnectionFactory;/** * 单消息队列通道 * Created by wangtf on 2015/11/16. * 生产者 */public class Producer {    private  final static  String QUEUE_NAME="hello";    public static void main(String[] argv) throws Exception {        ConnectionFactory factory = new ConnectionFactory();        factory.setHost("localhost");        Connection connection = factory.newConnection();        Channel channel = connection.createChannel();        channel.queueDeclare(QUEUE_NAME, false, false, false, null);        String message = "hello world";        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));        System.out.println(" [x] Sent '" + message + "'");        channel.close();        connection.close();    }}

import com.rabbitmq.client.*;import java.io.IOException;/** * Created by wangtf on 2015/11/16. * 消费者 */public class Consume {    private  final static  String QUEUE_NAME="hello";    public static void main(String[] argv) throws Exception {        ConnectionFactory factory = new ConnectionFactory();        factory.setHost("localhost");        Connection connection = factory.newConnection();        Channel channel = connection.createChannel();        channel.queueDeclare(QUEUE_NAME, false, false, false, null);        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");        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);    }}

转载于:https://my.oschina.net/u/2457218/blog/534754

你可能感兴趣的文章
Dubbo相关
查看>>
scss 在webpack 编码问题
查看>>
TypeError: s[y] is not a function 表单提交错误
查看>>
java使用nircmd代替cmd解决管理员权限问题
查看>>
JPA mappedBy属性
查看>>
开启服务器Mcrypt.so加密库的方法
查看>>
如何将SWT程序移植到Applet
查看>>
去好店,一个人在城市里面发生的故事
查看>>
点在面内(2)
查看>>
SPRING注解发布RMI/HTTPInvoker/Hessian/Burlap服务
查看>>
Jmeter(一)-精简测试脚本
查看>>
PowerDesigner显示Comment注释
查看>>
Learn Python the Hard Way: 类(Class)和对象(Object)
查看>>
centos安装或修复grub并使用grub引导系统
查看>>
ThinkPHP 上传文件方法
查看>>
Linux 系统 网卡RTL8723BE 信号差不稳定的解决办法
查看>>
getopt, optarg, optind, opterr, optopt
查看>>
为什么你这么努力,工作却还是没有起色?
查看>>
今天看了thinkcmf 和onethink
查看>>
root运行google chrome
查看>>