Spring cloud 使用 RabbitMq 01 (简单队列模式)

1.搭建项目基本环境

创建 publisher 和 consumer

1.1 导入相关依赖(AMQP)

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

1.2 编写application.yml 配置

server:
  port: 10001

spring:
  rabbitmq:
    host: 124.223.93.49 #地址
    port: 5672 #端口号
    virtual-host: / #虚拟主机
    username: xzh #登录用户名
    password: 123xzh #密码

2.在发布者Publisher用test发布消息

 2.1 发布消息前登录rabbitmq创建一个消息队列

 2.2 给消息队列发布消息

@RunWith(SpringRunner.class)
@SpringBootTest
@EnableRabbit
public class PublisherTest {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Test
    public void PTest(){
        String rabbitName="xzh";//名称
        String mess="hello rabbitmq";//发送的消息
        rabbitTemplate.convertAndSend(rabbitName,mess);
    }
}

2.3 查看消息

 3. consumer消费消息 (注意消费不可逆)

3.1 创建rabbitmq监听器

@Component
public class MqListener {
    @RabbitListener(queues = "xzh") //指定消息队列
    public void listenXzhQueue(String mess){
        System.out.println("mq消费消息:"+mess);
    }
}

 3.2 启动boot服务查看


版权声明:本文为qq_50598935原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。