spring boot集成rabbitmq

◇◆丶佛笑我妖孽 提交于 2019-12-10 01:06:34

1,新建spring boot项目,过程百度

2,引入maven依赖

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

 

3,修改rabbitmq配置文件

 

4,新建direct配置类

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


@Configuration
public class DirectConfig {

    @Bean
    public Queue directQueue(){
        return new Queue("direct",false); //队列名字,是否持久化
    }

    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange("direct",false,false);//交换器名称、是否持久化、是否自动删除
    }

    @Bean
    Binding binding(Queue queue, DirectExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("direct");

 

5,新建消息发送类

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

/**
 * 消息发送--生产消息
 */
@Component
public class Sender {

    @Autowired
    AmqpTemplate rabbitmqTemplate;

    public void send(String message){
        System.out.println("发送消息:"+message);
        rabbitmqTemplate.convertAndSend("direct",message);
    }

    public void send2(String message){
        System.out.println("发送消息:"+message);
        rabbitmqTemplate.convertAndSend("direct2",message);
    }

}

 

6,新建消息接收类

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


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

    @RabbitHandler
    public void handler(String message){
        System.out.println("接收消息:"+message);
    }

}

 

新建controller测试接口

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/rabbitmq")
public class MyRabbitmqController {


    @Autowired
    Sender sender;

    @RequestMapping("/sender")
    @ResponseBody
    public String sender(){
        System.out.println("send string:hello world");
        sender.send("hello world");
        return "sending...";
    }

    @RequestMapping("/sender2")
    @ResponseBody
    public String sender2(){
        System.out.println("send string:hello world");
        sender.send2("hello world2");
        return "sending2...";
    }

}

 

浏览器输入:http://localhost:8089/rabbitmq/sender

成功

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!