RabbitMQ案例之Publish/Subscribe

目的:把消息发到每一个消费者


rabitMq采用的订阅方式是通过queue与exchange之间的订阅方式


EmitLog.java发日志:

package yy.rabbitstudy.publish;

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

import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.amqp.core.ExchangeTypes;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class EmitLog {
    
    private static final String EXCHANGE_NAME="logs";

    public static void main(String[] args) {
        Connection connection=null;
        Channel channel =null;
        try{
            
            args=new String[]{"FirstMessage..","SecondMessage...","ThirdMessage..","FourthMessage..","FifthMessage...","6Message...","7Message...","8Message...","9Message...","10Message..."};
            ConnectionFactory factory=new ConnectionFactory();
            factory.setHost("localhost");
            connection=factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.FANOUT);
            System.out.println(channel.queueDeclare().getQueue());
            for (String string : args) {
                
                String message = getMessage(new String[]{string});
                //把消息发到exchange上
                channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
                System.out.println("[x] Sent" + message + "");
            }

        }catch(Exception e){
            
        }finally {
            if(channel!=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    private static String getMessage(String[] strings){
        if(strings.length<1)return "Hello World";
        return joinString(strings, " ");
    }
    
    private static String joinString(String[] strings,String delimiter){
        int length=strings.length;
        if(length==0)return "";
        StringBuilder words=new StringBuilder(strings[0]);
        for(int i=1;i<length;i++){
            words.append(delimiter).append(strings[i]);
        }
        return words.toString();
    }
}
ReceiveLogs.java 是收日志的浪费者

package yy.rabbitstudy.publish;

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

import org.springframework.amqp.core.ExchangeTypes;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class ReceiveLogs {

    private final static String EXCHANGE_NAME ="logs";
    public static void main(String[] args) throws IOException, TimeoutException {
        
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.FANOUT);
        String queueName=channel.queueDeclare().getQueue();
        System.out.println("[*] Waiting for messages. to exit press CTRL+C  "+queueName);
        
        channel.queueBind(queueName, EXCHANGE_NAME, "");
        //把通道交给消费者
        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 + "'");
            }
          };
          boolean autoAck=true;//当autoAck为false的时候,当消费都收到信息后,会回复队列,我收到信息了。这样就不会造成队列的消息流失。
          channel.basicConsume(queueName, autoAck, consumer);

    }
    


}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值