RabbitMQ 消息生产者 与 消费者

1–

import java.util.HashMap;
import java.util.Map;

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

public class Producer {

    public static void main(String[] args) throws Exception {
        //1.创建连接工厂,并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2.创建连接
        Connection connection = connectionFactory.newConnection();
        //3.创建连接通道
        Channel channel = connection.createChannel();
        Map<String,Object> headers = new HashMap<>();
        headers.put("my1", "111");
        headers.put("my2", "222");
        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .deliveryMode(2)//2表示持久化的投递,发送消息时,服务器重启,消息依然存在。1表示不是持久化:发送消息时服务器出现bug或者重启,该消息已经消失
                .contentEncoding("UTF-8")
                .expiration("10000")//过期时间
                .headers(headers)//自定义属性
                .build();
        
        
        //4.发送数据,exchange,routingkey,props:消息附加属性,body:消息实体
        for (int i = 0; i < 5; i++) {
            String msg = "lulu张雪喜欢你";
            channel.basicPublish("", "lulu", properties, msg.getBytes());
            System.out.println(msg);
        }
        //5.关闭连接:由小到大
        channel.close();
        connection.close();
        
    }
}
import java.util.Map;

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

public class Consumer {
    public static void main(String[] args) throws Exception {
        //1.创建连接工厂,并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2.创建连接
        Connection connection = connectionFactory.newConnection();
        //3.创建连接通道
        Channel channel = connection.createChannel();
        //4.生命一个队列   1. 队列称,2.持久化,3.独占:只只有改通道能监听,4.脱离exchange会自动删除5.扩展参数
        String queueName = "lulu";
        channel.queueDeclare(queueName, true, false, false, null);
        //5.创建一个消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        //6.设置channel   1.队列名称,2.自动签收 3.消费者对象
        channel.basicConsume(queueName, true, queueingConsumer);
        //7.获取消息   会一直阻塞。可以设置时间通过                                                                   
        while (true) {
            System.out.println("开始消费数据");
            
            Delivery delivery = queueingConsumer.nextDelivery();//没有设置时间一直阻塞。
            
            String msg = new String(delivery.getBody());//消息实体body
            Map<String,Object> headers = delivery.getProperties().getHeaders();
            System.out.println(headers.get("my1"));
            System.out.println(headers.get("my2"));
            //Envelope envelope = delivery.getEnvelope();//消息属性     

            
        }

2–

 public void fireEngineSend2(String message) {
    try {
      // 创建工厂
      factory = new ConnectionFactory();
      // 设置
      factory.setHost(host);
      factory.setUsername(username);
      factory.setPassword(password);
      factory.setPort(port);
      factory.setVirtualHost("/");
      try (Connection connection = factory.newConnection();
          Channel channel = connection.createChannel()) {
        channel.queueDeclare(queueName, false, false, false, null);
        channel.basicPublish("", queueName, null, message.getBytes(StandardCharsets.UTF_8));
        System.out.println(" [x] Sent '" + message + "'");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (TimeoutException e) {
      e.printStackTrace();
    } finally {
      try {
        // 关闭通道
        if (channel != null) {
          channel.close();
        }
        // 关闭连接
        if (connection != null) {
          connection.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      } catch (TimeoutException e) {
        e.printStackTrace();
      }
    }
  }
  public void fireEngineReceive2() {
    try {
      // 创建工厂
      factory = new ConnectionFactory();
      // 设置
      factory.setHost(host);
      factory.setUsername(username);
      factory.setPassword(password);
      factory.setPort(port);
      factory.setVirtualHost("/");
      // 创建连接
      Connection connection = factory.newConnection();
      Channel channel = connection.createChannel();

      channel.queueDeclare(queueName, false, false, false, null);
      System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

      DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        String message = new String(delivery.getBody(), "UTF-8");
        System.out.println(" [x] Received '" + message + "'");
      };
      channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
      });

    } catch (IOException e) {
      e.printStackTrace();
    } catch (TimeoutException e) {
      e.printStackTrace();
    }
  }

3–

  public void fireEngineSend(){

    try {
    // 创建工厂
    factory = new ConnectionFactory();
    // 设置
    factory.setHost(host);
    factory.setUsername(username);
    factory.setPassword(password);
    factory.setPort(port);
    factory.setVirtualHost("/");
    Connection connection = null;
      connection = factory.newConnection();
      Channel channel = connection.createChannel();

      String exchange = "fire_engine";
      String routingKey = "consumer.save";
      String msg = "Hello RabbitMQ Consumer Message";

      for(int i =0; i<5; i ++) {
        try {
          channel.basicPublish(exchange, routingKey, true, null, msg.getBytes());
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (TimeoutException e) {
      e.printStackTrace();
    }

  }
  public void fireEngineReceive() {
    try {
      // 创建工厂
      factory = new ConnectionFactory();
      // 设置
      factory.setHost(host);
      factory.setUsername(username);
      factory.setPassword(password);
      factory.setPort(port);
      Connection connection = null;
      connection = factory.newConnection();
      Channel channel = connection.createChannel();
      channel.exchangeDeclare(exchangeName, "topic", true, false, null);
      channel.queueDeclare(queueName, true, false, false, null);
      channel.queueBind(queueName, exchangeName, routingKey);
      channel.basicConsume(queueName, true, new MyConsumer(channel));

    } catch (IOException e) {
      e.printStackTrace();
    } catch (TimeoutException e) {
      e.printStackTrace();
    }
  }
/**
 * 实现自己的Consumer
 */
public class MyConsumer extends DefaultConsumer {

    public MyConsumer(Channel channel){
        super(channel);
    }


    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        System.err.println("-----------consume message----------");
        System.err.println("consumerTag: " + consumerTag);
        System.err.println("envelope: " + envelope);
        System.err.println("properties: " + properties);
        System.err.println("body: " + new String(body));
    }
}

4–

/**
 * @author MrBird
 */
@EnableAsync
@SpringBootApplication
@EnablePatrolCloudResourceServer
@EnableTransactionManagement
@EnableDistributedTransaction
@EnableBinding(Sink.class)
@MapperScan("com.data.mapper")
public class PatrolServerDataProcessApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(PatrolServerDataProcessApplication.class)
                .web(WebApplicationType.SERVLET)
                .run(args);
      RabbitmqUtil rabbitmqUtil = new RabbitmqUtil();
      rabbitmqUtil.fireEngineSend(); //测试用
      rabbitmqUtil.fireEngineReceive();
    }
}
  @StreamListener(Sink.INPUT)
  public void handle(Person person) {
    System.out.println("Received: " + person);
  }

  public static class Person {
    private String name;
    public String getName() {
      return name;
    }
    public void setName(String name) {
      this.name = name;
    }
    public String toString() {
      return this.name;
    }
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值