Springboot集成RabbitMQ

最终实现效果如下,每三秒打印消息。

首先打开IDEA,创建maven java project。

在pom.xml添加依赖,其完整源码如下。

    4.0.0

    com.zhenqi
    springboot-rabbitmq
    0.0.1-SNAPSHOT
    jar

    Springboot_RabbitMQ
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.7
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-amqp
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

而后在 Springboot启动类编辑以下代码。

package com.zhenqi.springboot.study;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

@SpringBootApplication
@EnableScheduling//启用任务调度.
@RabbitListener(queues="study")//启用Rabbit队列监听study key.
public class SpringbootRabbitMqApplication {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Scheduled(fixedDelay=3000)//3s执行1次此方法;
    public void send(){
        rabbitTemplate.convertAndSend("study","zhenqi");
    }

    @Bean
    public Queue studyQueue(){
        return new  Queue("study");
    }

    //接收到消息处理.
    @RabbitHandler
    public void onMessage(@Payload String study){
        System.out.println(" >>> "+new Date() + ": " + study);
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootRabbitMqApplication.class, args);
    }
}

最后附上配置文件 application.properties。

spring.application.name=Springboot-Rabbitmq
spring.rabbitmq.host=192.168.146.128
spring.rabbitmq.port=5672
spring.rabbitmq.username=openstack
spring.rabbitmq.password=rabbitmq
CSDN博客稿源:CSDN博客 (源链) | 来自的投递 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合技术 » Springboot集成RabbitMQ

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录