RabbitMq(java代码实践部分)

技术摘要:

Java框架SpringBoot   +  RabbitMq

前期准备:

启动rabbitMq (咱们在复习一下)

进入到我们的RabbitMq安装文夹

cd /
D:

cd gj/rabbitServe/rabbitmq_server-3.12.1/sbin   (我这是进入我自己的安装目录)

rabbitmq-plugins enable rabbitmq_management

rabbitmq-server start

指令打完我们就可以登录我们的本地RabbitMq(http://127.0.0.1:15672)

 还是给大家截个图吧。

然后启动我们的springBoot 项目

简单说一下 SpringBoot 引入的依赖吧

<!--rabbitMq-->
<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.10.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!--rabbitMq--> 

yml文件配置

spring:
  mq:
   host: 127.0.0.1
   port: 5672
   username: guest
   password: guest
   virtualhost: /
   exchange: sync.target.queue.direct
   queue.fromGw: sync.target.queue
   queue:
    fromGw: hello2

后端的依赖 以及 配置文件 准备好后

我们分两个部分

1.(当前是监听部分):将RabbitMq的对应的queue最新内容接收到

两部分准备:配置类  监听类  (将配置类注册到监听类上)上干货

配置类:

package com.example.demo.rabbitMq;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class RabbitConfig {

    @Value("${spring.mq.queue.fromGw}")
    public String queue_fromGw;

    @Bean
    public Queue fromGw() {
        return new Queue(queue_fromGw);
    }

    @Bean
    CachingConnectionFactory connectionFactory(@Value("${spring.mq.port}") int port,
                                               @Value("${spring.mq.host}") String host,
                                               @Value("${spring.mq.username}") String userName,
                                               @Value("${spring.mq.password}") String password,
                                               @Value("${spring.mq.virtualhost}") String vhost) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        System.out.println(host);
        connectionFactory.setVirtualHost(vhost);
        System.out.println(vhost);
        connectionFactory.setPort(port);
        System.out.println(port);
        connectionFactory.setUsername(userName);
        System.out.println(userName);
        connectionFactory.setPassword(password);
        System.out.println(password);
        return connectionFactory;
    }

    @Bean
    public SimpleMessageListenerContainer modbusMessageContainer(WaMingQueueListener receiver, ConnectionFactory connectionFactory) throws AmqpException, IOException {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueueNames(queue_fromGw);
        System.out.println(queue_fromGw);
        container.setExposeListenerChannel(true);
        //container.setAcknowledgeMode(AcknowledgeMode.MANUAL);//设置确认模式为手工确认
        container.setMessageListener(receiver);//监听处理类
        return container;
    }

}

监听类

package com.example.demo.rabbitMq;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class WaMingQueueListener  implements ChannelAwareMessageListener    {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        byte[] body = message.getBody();
        //     logger.info("Listener RabbitMQ Msg :" + new String(body));
        System.out.println("Listener RabbitMQ Msg :" + new String(body));
        // 实际业务处理
    }

    @Override
    public void onMessage(Message message) {

    }

    @Override
    public void containerAckMode(AcknowledgeMode mode) {

    }

    @Override
    public boolean isAsyncReplies() {
        return false;
    }

    @Override
    public void onMessageBatch(List<Message> messages) {

    }

    @Override
    public void onMessageBatch(List<Message> messages, Channel channel) {

    }
}

然后启动项目 等待接收新的MQ消息吧!!!!...

2.(当前是生产者部分):将消息发送到RabbitMq的对应的queue

package com.example.demo.rabbitMq;

import com.example.demo.vo.User;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.json.JSONObject;

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

/**
 * 生产者
 */
public class Producer {

    // 定义两个队列和一个交换机
    private final static String QUEUE_EMAIL = "queue_email";
    private final static String QUEUE_SMS = "queue_sms";
    private final static String EXCHANGE_NAME = "exchange_fanout_1";
    private final static String QUEUE_NAME = "hello1";
    private final static String QUEUE_NAME1 = "hello2";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        // 设置虚拟主机 一个mq的服务可以设置多个虚拟机,每个虚拟机相当于独立的mq
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = null;
        Channel channel = null;

        try {
            connection = factory.newConnection();
            // 创建内部会话通道,生产者和mq服务通信都在channel中完成
            channel = connection.createChannel();
            // 声明交换机
            /**
             * 1. 交换机名称
             * 2、交换机类型:
             *  FANOUT:对应的模式就是 发布/订阅模式
             *  DIRECT:对应 路由(Routing) 的工作模式
             *  TOPIC:对应 Topics 工作模式
             *  HEADERS: 对应 HEADERS 工作模式
             */
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
            // 声明创建队列,如果没有,则创建


           // System.out.println(channel.queueDeclarePassive("123").getQueue());

            channel.queueDeclare(QUEUE_EMAIL,false,false,false, null);
            channel.queueDeclare(QUEUE_SMS,false,false,false,null);
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            channel.queueDeclare(QUEUE_NAME1,false,false,false,null);





            // 交换机队列绑定
            /**
             * 1 queue 队列名称
             * 2 exchange 交换机名称
             * 3 routingKey 路由Key 发布订阅模式中 设置为""
             */
            channel.queueBind(QUEUE_EMAIL,EXCHANGE_NAME,"");
            channel.queueBind(QUEUE_SMS,EXCHANGE_NAME,"");
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");
            channel.queueBind(QUEUE_NAME1,EXCHANGE_NAME,"");
            String message = "接好了,SMS和EMAIL~~";
            // 发送消息
            // 参数:String exchange, String routingKey, BasicProperties props, byte[] body
            /**
             * exchange:交换机 如果不指定(""),就默认交换机
             * routingKey:路由key;交换机根据路由key将消息转发到指定的队列,如果使用默认交换机,routingKey为队列名称
             * props:额外属性
             * body:消息内容
             */
            for(int i=0;i<10;i++){
                User user = new User("名字"+i,"电话1389098789"+i,"身份证号22010319950113041"+i,"男","年龄"+i);
                JSONObject object = new JSONObject(user);
                String json = object.toString();
                channel.basicPublish(EXCHANGE_NAME,"",null,json.getBytes());
                System.out.println("send message: "+message);
            }
        } finally {
            channel.close();
            connection.close();
        }

    }

}

然后我们运行一下这个main方法 看SpringBoot 是否接收到了 我这就去实验一下...

感觉我流了一个小小的坑

就是总会说我的 queue已经被占用。

所以 我总是会去清理queue。没用过的小伙伴 应该不会出现这个问题。你们 就小心吧。

例子出来了 ,这里就不过多的 说太多的 讲解。实现过程在去吸收...88 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值