zoukankan      html  css  js  c++  java
  • 【Spring Boot】Spring Boot之整合RabbitMQ并实现消息的发送和接收

    一、项目配置

    1)引入maven坐标

            <!--amqp-->
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-amqp</artifactId>
                    <version>2.0.3.RELEASE</version>
                </dependency>

    2)application.yml加入RabbitMQ的连接配置

    spring.rabbitmq.host: localhost
    spring.rabbitmq.port: 5672
    spring.rabbitmq.username: guest
    spring.rabbitmq.password: guest

    二、消息的发送和接收

    1)创建指定名称的消息队列

    @Configuration
    public class RabbitConfig {
        @Bean
        public Queue helloQueue() {
            return new Queue("hello");
        }
    }

    2)创建消息接收者

    @Component
    @RabbitListener(queues = "hello")
    public class Receiver {
        @RabbitHandler
        public void process(String hello) {
            System.out.println("Receiver : " + hello);
        }
    }

    3)创建消息发送着

    @Component
    public class Sender {
    
        @Autowired
        private AmqpTemplate rabbitTemplate;
    
        public void send() {
            String context = "hello " + new Date();
            System.out.println("Sender : " + context);
            this.rabbitTemplate.convertAndSend("hello", context);
        }
    }

    4)创建发送消息的测试类

    @RunWith(SpringRunner.class)
    @WebAppConfiguration
    @SpringBootTest
    public class RabbitMQSenderTest {
    
        @Autowired
        private Sender sender;
    
        @Test
        public void hello() throws Exception {
            sender.send();
        }
    
    }
  • 相关阅读:
    error: with modifiers "public "
    移除元素
    删除有序数组中的重复项
    最长公共前缀
    如何杀死window进程
    IDEA卡顿问题
    合并两个有序链表
    开闭原则
    字符集和sql语句GROUPBY查询的版本问题
    里氏替换原则
  • 原文地址:https://www.cnblogs.com/756623607-zhang/p/11470816.html
Copyright © 2011-2022 走看看