springBoot+RabbitMQ例子

demo目录

贴代码

1.ProducerConfig.java

package com.test.config;

import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by admin on 2017/6/1 13:23.
 */
@Configuration
public class ProducerConfig {
    @Bean
    public RabbitMessagingTemplate msgMessageTemplate(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        //参数列表分别是:1.交换器名称(default.topic 为默认值),2.是否长期有效,3.如果服务器在不再使用时自动删除交换器
        TopicExchange exchange = new TopicExchange("default.topic", true, false);
        rabbitAdmin.declareExchange(exchange);
        //1.队列名称,2.声明一个持久队列,3.声明一个独立队列,4.如果服务器在不再使用时自动删除队列
        Queue queue = new Queue("test.demo.send", true, false, false);
        rabbitAdmin.declareQueue(queue);
        //1.queue:绑定的队列,2.exchange:绑定到那个交换器,3.test2.send:绑定的路由名称
        rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("test2.send"));
        return RabbitUtil.simpleMessageTemplate(connectionFactory);
    }
}

2.RabbitMQConfig.java

package com.test.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by admin on 2017/6/1 11:26.
 */
@Configuration
public class RabbitMQConfig {
    /**
     * 注入配置文件属性
     */
    @Value("${spring.rabbitmq.addresses}")
    String addresses;//MQ地址
    @Value("${spring.rabbitmq.username}")
    String username;//MQ登录名
    @Value("${spring.rabbitmq.password}")
    String password;//MQ登录密码
    @Value("${spring.rabbitmq.virtual-host}")
    String vHost;//MQ的虚拟主机名

    /**
     * 创建 ConnectionFactory
     *
     * @return
     * @throws Exception
     */
    @Bean
    public ConnectionFactory connectionFactory() throws Exception {
        return RabbitUtil.connectionFactory(addresses, username, password, vHost);
    }

    /**
     * 创建 RabbitAdmin
     *
     * @param connectionFactory
     * @return
     * @throws Exception
     */
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) throws Exception {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        return rabbitAdmin;
    }

}

3.RabbitUtil.java

package com.test.config;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.messaging.converter.GenericMessageConverter;

/**
 * RabbitMQ 公共类
 * Created by admin on 2017/6/1 11:25.
 */
public class RabbitUtil {

    /**
     * 初始化 ConnectionFactory
     *
     * @param addresses
     * @param username
     * @param password
     * @param vHost
     * @return
     * @throws Exception
     */
    public static ConnectionFactory connectionFactory(String addresses, String username, String password, String vHost) throws Exception {
        CachingConnectionFactory factoryBean = new CachingConnectionFactory();
        factoryBean.setVirtualHost(vHost);
        factoryBean.setAddresses(addresses);
        factoryBean.setUsername(username);
        factoryBean.setPassword(password);
        return factoryBean;
    }

    /**
     * 初始化 RabbitMessagingTemplate
     *
     * @param connectionFactory
     * @return
     */
    public static RabbitMessagingTemplate simpleMessageTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        RabbitMessagingTemplate rabbitMessagingTemplate = new RabbitMessagingTemplate();
        rabbitMessagingTemplate.setMessageConverter(new GenericMessageConverter());
        rabbitMessagingTemplate.setRabbitTemplate(template);
        return rabbitMessagingTemplate;
    }
}

4.Student.java

package com.test.model;

import java.io.Serializable;

/**
 * Created by admin on 2017/6/1 13:36.
 */
public class Student implements Serializable {
    private String name;
    private Integer age;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

5.Consumers.java

package com.test.task;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

/**
 * Created by admin on 2017/6/1 13:29.
 */
@Service
public class Consumers {

    @RabbitListener(
            admin = "rabbitAdmin",
            bindings = @QueueBinding(
                    value = @Queue(value = "test.demo.send", durable = "true", autoDelete = "false"),
                    exchange = @Exchange(value = "default.topic", durable = "true", type = "topic"),
                    key = "test2.send")
    )
    public void test(Object obj) {
        System.out.println("receive....");
        System.out.println("obj:" + obj.toString());
    }
}

6.Producers.java

package com.test.task;

import com.test.model.Student;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by admin on 2017/6/1 13:35.
 */
@Service
public class Producers {

    @Autowired
    RabbitMessagingTemplate rabbitSendTemplate;

    public void send(Student student) {
        System.out.println("send start.....");
        rabbitSendTemplate.convertAndSend(
                "default.topic",
                "test2.send",
                student);
    }
}

7.TestController.java

package com.test.test;

import com.test.model.Student;
import com.test.task.Producers;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by admin on 2017/6/1 13:38.
 */
@Controller
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    Producers producers;

    @RequestMapping(value = "/send", method = RequestMethod.GET)
    @ResponseBody
    public void test() {
        Student s = new Student();
        s.setName("zhangsan");
        s.setAddress("wuhan");
        s.setAge(20);
        producers.send(s);
    }

}

8.MainApplication.java

package com.test;

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

/**
 * Created by admin on 2017/6/1 11:19.
 */
@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        System.getProperties().put("test", "test");
        SpringApplication.run(MainApplication.class, args);

    }
}

9.application.yml

server:
    address: 192.168.200.117 #自己主机的IP地址
    port: 8000 #端口
spring:
  rabbitmq:
    addresses: 192.168.200.119:5672 #MQ IP 和 端口
    username: admin #MQ登录名
    password: 123456 #MQ登录密码
    virtual-host: test #MQ的虚拟主机名称

10.build.gradle

group ‘rabbitmqtest‘
version ‘1.0-SNAPSHOT‘

apply plugin: ‘java‘

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: ‘junit‘, name: ‘junit‘, version: ‘4.11‘
    testCompile("org.springframework.boot:spring-boot-starter-test:1.3.5.RELEASE")
    compile("org.springframework.boot:spring-boot-starter-web:1.3.5.RELEASE")
    compile(group: ‘org.springframework.amqp‘, name: ‘spring-rabbit‘, version: "1.6.1.RELEASE")
}

11.settings.gradle

rootProject.name = ‘rabbitmqtest‘

页面访问 192.168.200.117:8000/test/send  可以看到控制台有日志输出,发送的消息立即消费掉了

MQ的队列里面也是空的

如果把消费者的代码注掉,再访问刚才的 url 地址 队列里面就会多一条

123

时间: 2024-08-29 04:04:48

springBoot+RabbitMQ例子的相关文章

springboot+rabbitmq整合示例程

关于什么是rabbitmq,请看另一篇文: http://www.cnblogs.com/boshen-hzb/p/6840064.html 一.新建maven工程:springboot-rabbitmq 二.引入springboot和rabbitmq的依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quo

SpringBoot RabbitMQ 延迟队列代码实现

场景 用户下单后,如果30min未支付,则删除该订单,这时候就要可以用延迟队列 准备 利用rabbitmq_delayed_message_exchange插件: 首先下载该插件:https://www.rabbitmq.com/community-plugins.html 然后把该插件放到rabbitmq安装目录plugins下: 进入到sbin目录下,执行"rabbitmq-plugins.bat enable rabbitmq_delayed_message_exchange";

springboot rabbitmq整合

这一篇我们来把消息中间件整合到springboot中 ===================================================================== 首先在服务器上安装rabbitmq的服务,用docker拉取即可,不再详细描述. 直接来撸代码 首先我们先添加rabbitmq的依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId&g

带着新人学springboot的应用06(springboot+RabbitMQ 中)

上一节说了这么多废话,看也看烦了,现在我们就来用鼠标点点点,来简单玩一下这个RabbitMQ. 注意:这一节还是不用敲什么代码,因为上一节我们设置了那个可视化工具,我们先用用可视化工具熟悉一下流程. 打开可视化页面,http://localhost:15672 顺便说一下RabbitMQ中的持持久化:这里持久化分为三种:消息持久化,交换器持久化,队列持久化... 举个例子,就简单说说交换器持久化,其实就是为了防止将消息发到交换器了,但是RabbitMQ服务器突然暴毙,没用了,那数据不就丧失了么?

springboot RabbitMQ 配置

引用自 http://www.cnblogs.com/ityouknow/p/6120544.html 自己留一份 记录一下 RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用. 消息中间件在互联网公司的使用中越来越多,刚才还看到新闻阿里将RocketMQ捐献给了apache,当然了今天的主角还是讲RabbitMQ.消息中间件最主要的作用是解耦,中间件最标准的用法是生产者生产消息传送到队列,消费者从队列中拿取消息并处理,生产者不用关心是谁来

带着新人学springboot的应用07(springboot+RabbitMQ 下)

说一两句废话,强烈推荐各位小伙伴空闲时候也可以写写自己的博客!不管水平高低,不管写的怎么样,不要觉得写不好或者水平不够就不写了(咳,我以前就是这样的想法...自我反省!). 但是开始写博客之后,你会发现很多你以为自己会的东西其实你并不会,然后你会经常在头脑中不断的搜索有关的片段,或者去别的大神博客里到处找有关的资料,最后领悟了属于自己的东西!然后再写出来和别人分享,别人也会给你点意见,你也会慢慢的改进.这不就是学习+复习+巩固+创新+分享+改进的这么的一个过程吗? 以前看过曹雪芹的红楼梦,让我印

SpringBoot+RabbitMQ启动出现报错问题总结org.springframework.amqp.AmqpConnectException: java.net.ConnectException和 java.net.SocketException: Socket Closed

环境: RabbitMQ是安装在虚拟机中Centos7 版本: RabbitMQ 3.5.7 SpringBoot 2.1.5 检查: 先检查端口,15672是插件的端口,在SpringBoot的配置文件中,应该使用5672 登录用户,如果你使用的是guest默认的用户,那么默认情况下只能在localhost登录,解决: 进入到etc的目录: 再进入到rabbitmq的目录并且在此目录下编辑一个名为rabbitmq.config的文件(注意:名字一定要是这个) 进入到文件编辑框,,加上如下的代码

SpringBoot+RabbitMQ实现消息可靠性投递

摘抄自简书:https://www.jianshu.com/p/9feddd4af8ee RabbitMQ是目前主流的消息中间件,非常适用于高并发环境.各大互联网公司都在使用的MQ技术,晋级技术骨干.团队核心的必备技术! 谈到消息的可靠性投递,无法避免的,在实际的工作中会经常碰到,比如一些核心业务需要保障消息不丢失,接下来我们看一个可靠性投递的流程图,说明可靠性投递的概念: Step 1: 首先把消息信息(业务数据)存储到数据库中,紧接着,我们再把这个消息记录也存储到一张消息记录表里(或者另外一

springboot~rabbitmq的队列初始化和绑定

配置文件,在rabbit中自动建立exchange,queue和绑定它们的关系 代码里初始化exchange 代码里初始化queue 代码里绑定exchange,queue和routekey 配置文件,直接声明vhost 代码里初始化exchange /** * rabbitMq里初始化exchange. * * @return */ @Bean public TopicExchange crmExchange() { return new TopicExchange(EXCHANGE); }