Java编程中Spring Boot整合RabbitMQ

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(21977)   2024-03-18 14:17:48

Java编程中Spring Boot整合RabbitMQ实现消息中间件RabbitMQ的使用

 1 主要用spring-boot-starter-amqp来整合RabbitMQ和SpringBoot

 2 pom.xml文件中加入依赖
 

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
            <!--<scope>provided</scope>-->
  </dependency>

 3编写配置文件application.yml

spring:
  application:
    name: rabbitmq-test
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

4 Java编程中编写Sender并使用注解@Component注册为spring框架容器组件

@Component
public class Sender {
    @Autowired
    private AmqpTemplate amqpTemplate;

    public void send() throws Exception {
        String message= "hello" + new Date();
        System.out.println("Sender:"+context);
        this.amqpTemplate.convertAndSend("test_queue_name",message);
    }
}

5 Java编程中编写Reveiver并使用注解@Component注册为spring框架容器组件同时监听队列hello,并用RabbitHandler来处理请求。queues = "test_queue_name"这里的test_queue_name就是发送消息时候的队列名称

@Component
@RabbitListener(queues = "test_queue_name")
public class Receiver {

    @RabbitHandler
    public void process(String message){
        System.out.println("Receiver:"+message);
    }
}

6Java编程中编写刚刚用到的hello队列的配置类

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

7 Java编程中编写单元测试类Test,调用Sender的方法发送message,这样Receiver就能自动监听并在主类哪里输出了

@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {

    @Autowired
    private Sender sender;

    @org.junit.Test
    public void hello() throws Exception {
        sender.send();
    }
}
标签2: java编程 spring boot
地址:https://www.leftso.com/article/95.html

相关阅读

Java编程中Spring Boot整合RabbitMQ实现消息中间件RabbitMQ的使用
Java编程中spring boot项目如何获取spring容器applicationContext
Java编程之Spring Boot通过JMSTemplate 整合ActiveMQ
Java编程之Spring Boot中使用jsp视图模板
Java编程中spring boot项目动态添加拦截器Interceptor
Java编程之spring boot FastDFS Java client使用,Java编程,FastDFS Java客户端
Java编程之spring boot shiro redis整合基于角色和权限的安全管理,Java编程,spring boot,shiro,权限控制
spring boot 入门之security oauth2 jwt完美整合例子,Java编程中spring boot框架+spring security框架+spring security o...
Java编程之Spring Boot 使用SLF4J Logging,spring boot,SLF4J
Java编程中使用spring boot1.5.2框架整合spring data mongodb10.1,来使用mongodb数据库