spring boot 集成rabbitmq(9步搞定)

前言:最近公司有使用到spring boot rabbitmq,使用了总归是要记录一下,主要是加强巩固。

 

首先我们创建一个spring boot项目

第一步:pom.xml引入amqp

 

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

第二步:在application.properties修改默认的配置

 

 
spring.rabbitmq.host=#.#.#.#
spring.rabbitmq.port=5672
spring.rabbitmq.username=xubing
spring.rabbitmq.password=123456

第三步:springboot程序入口

 

package com.xubing;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootrabbitmqApplication {

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

 

第四步:新建一个配置文件,用于创建声明队列,并将队列绑定到交换器(未来简单起见我们使用direct交换器,省略了绑定队列到交换器的操作)

 

package com.xubing.configuration;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by xubing on 2018/3/10.
 */
@Configuration
public class RabbitmqConfiguration {


    /**
     * 实例化队列
     * @return
     */
    @Bean
    public Queue Queue(){
        return new Queue("helloworld");
    }



}

 

第五步:创建一个生成者

 

package com.xubing;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by xubing on 2018/3/10.
 */
@Component
public class Producer {

    @Autowired
   public AmqpTemplate amqpTemplate;

   public  void sendMessage(String queueName,String message ){
       amqpTemplate.convertAndSend(queueName,message);
   }


}

第六步:编写单元测试:

 

package com.xubing;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProducerTests {

   @Autowired
   Producer producer;

   @Test
   public void testSend(){
      String queueName="helloworld";
      String message="你好呀";
      producer.sendMessage(queueName,message);
   }


}

第七步:执行之前从rabbitmq mananger查看队列信息

 

第8步:开始执行单元测试

单元测试结果

第9步:执行成功ok,我们在去rabbitmq manager查看一下

 

 

最后附上github源码地址:点击打开链接

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值