RabbitMQ的代码学习(消费者)

(Python实现)

# coding: utf-8
import pika
import os
import json
from kafka import KafkaProducer
from kafka.errors import KafkaError

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
class GetRabbitMq:
    def __init__(self,username,password,host,queueName):
        self.username = username
        self.password = password
        self.host = host
        self.queueName = queueName
        self.connection = None
        self.producer = None
        try:
            self.credentials = pika.PlainCredentials(self.username,self.password)
            self.connection = pika.BlockingConnection(pika.ConnectionParameters(self.host,5672,'/',self.credentials))
            self.channel = self.connection.channel()
            self.channel.queue_declare(queue=self.queueName, durable=True)#如果没有这个队列,就创建这个队列
        except Exception, e:
            print e

    def sendjsondata(self, params):
    	print params

    def callback(self,ch, method,properties,body):
        self.sendjsondata(body)
        #反馈信息
        ch.basic_ack(delivery_tag=method.delivery_tag)

if __name__ == "__main__":
    rabbitMqMessage = GetRabbitMq('username','password','192.168.0.1','queueName')
    # True:收到消息会给rabbit反馈信息,且彻底消费消息,False,不给反馈,rabbit将消息标识为Unacked
    rabbitMqMessage.channel.basic_consume(queue=rabbitMqMessage.queueName,on_message_callback=rabbitMqMessage.callback,exclusive=False)
    rabbitMqMessage.channel.start_consuming()

(java实现)

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMQConsumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("root");
        factory.setPassword("123456");
        //设置 RabbitMQ地址
        factory.setHost("140.143.17.1");
        //建立到代理服务器到连接
        Connection conn = factory.newConnection();
        //获得信道
        Channel channel = conn.createChannel();
        //声明交换器
        String exchangeName = "hello";
        channel.exchangeDeclare(exchangeName,"direct",true);

        //声明队列
        //String queueName = channel.queueDeclare().getQueue();
        //可指定queueName来获取队列消息。
        String queueName = "hello";
        String routingKey = "hola";
        //绑定队列,通过键 hola 将队列和交换器绑定起来
        channel.queueBind(queueName,exchangeName,routingKey);

        while (true){
            //消费消息
            boolean autoAck = false;
            String consumerTag = "";
            channel.basicConsume(queueName,autoAck,consumerTag,new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) throws IOException {

                    String routingKey = envelope.getRoutingKey();
                    String contentType = properties.getContentType();
                    System.out.println("消费者的路由键:"+routingKey);
                    System.out.println("消费者的内容类型:"+contentType);
                    long deliveryTag = envelope.getDeliveryTag();
                    //确认消息
                    channel.basicAck(deliveryTag,false);
                    System.out.println("消费的消息体内容:");
                    String bodyStr = new String(body,"UTF-8");
                    System.out.println(bodyStr);
                    super.handleDelivery(consumerTag, envelope, properties, body);
                }
            });
        }
    }
}

你可能感兴趣的:(消息队列)