RabbitMq的配置和使用

要使用RabbitMq可以先去spring官网上找到spring-rabbitMq里面有配置和maven依赖

本人的配置使用的是springboot框架
下面是maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-messaging-rabbitmq</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

下面的是RabbitMq的配置类

package com.example.demo.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *这是一个RabbitMqConfig的一个配置类,
 */
@Configuration
public class RabbitMqConfig {

    private static final String QUENE_NAME="a.quene";//这个是队列的名称
    private static final String TASK_EXCHANGE="a.exchange.name";//这个是交换机的名称

    @Bean
    public RabbitTemplate getRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate=new RabbitTemplate(connectionFactory);//Create a rabbit template with default strategies and settings.
        rabbitTemplate.setMessageConverter(jsonConverter());
        return rabbitTemplate;
    }
    @Bean
    public MessageConverter jsonConverter() {
        return new Jackson2JsonMessageConverter();//以json的格式传递数据
    }


    public static final String suffix = Long.toString(System.currentTimeMillis());//用时间戳就是为了保证名字的唯一性
    public final static boolean durable = false;
    public final static boolean autoDelete = true;


    /**
     * 交换机
     * @return
     */
    @Bean
    public FanoutExchange taskExchange() {
        /**
         * durable: true if we are declaring a durable exchange (the exchange will survive a server restart)
         * 意思就是:如果我们宣布一个持久的交换机,交换器将在服务器重启后继续存在。false就是服务器重启后将不在存在
         * autoDelete:true if the server should delete the exchange when it is no longer in use
         * 意思就是:如果长时间不用这个交换机,就删掉这个交换机
         */

        return new FanoutExchange(TASK_EXCHANGE + "." + suffix, durable, autoDelete);
    }
    /**
     * 一个队列
     * @return
     */
    @Bean
    public Queue taskNoticeQueue() {
        /**
         * exclusive: true if we are declaring an exclusive queue (the queue will only be used by the declarer's connection)
         *如果我们声明一个独占队列,队列只会被声明者的连接使用
         */
        return new Queue(QUENE_NAME + "." + suffix, durable, false, autoDelete);
    }

    /**
     * 将队列和交换机绑定起来
     * @param taskExchange
     * @param taskNoticeQueue
     * @return
     */
    @Bean
    public Binding taskNoticeBinding(FanoutExchange taskExchange,
                                     Queue taskNoticeQueue) {
        return BindingBuilder.bind(taskNoticeQueue).to(taskExchange);
    }
    /**
     * 这里顺便说一下@Bean这个注解,@Bean的方法名就是xml中的bean的ID,生成的对象的引用名称
     * 就比如@Autowired private User users,这个users就是那个方法名
     */


}

下面是rabbit的时间监听的service

package com.example.demo.service;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by lijunnan on 2017/7/20.
 */
@Service
public class RabbitMqService {

    public static final String TASK_PUSH_REDIS_CHANNEL = "TASK_MESSAGE";

    @Qualifier("getRabbitTemplate")
    @Autowired
    private RabbitTemplate taskRabbitTemplate;
    @Value("#{taskExchange.name}")//交换机的名称
    private String exchangeName;

    /**
     * 监听事件,只要队列的名称是taskNoticeQueue.name的值一樣的就能监听
     * @param ss 传递的数据
     */
    @RabbitListener(queues = "#{taskNoticeQueue.name}")
    public void receiveEvent4Notice(String ss) {
        System.out.println("我是监听消息的,我监听成功了值:"+ss);
    }

    /**
     * @param ss 就是要发送的一个数据
     */
    public void invokeTaskEvent(String ss) {
        taskRabbitTemplate.convertAndSend(exchangeName, "",ss);
    }


}

下面的是调用消息的生产者

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

/**
 * 这个类实现了一个CommandLineRunner接口,
 * 这个接口就是在服务器启动完成之前要做一些事情
 */
@Service
public class RabbitMqListenerDemo implements CommandLineRunner{
    @Autowired
    private RabbitMqService rabbitMqService;

    @Override
    public void run(String... strings) throws Exception {
        //发送一个消息
        rabbitMqService.invokeTaskEvent("hahahahhahahahahhahah");
    }
}

application.yml中的rabbit配置不能少,连接rabbitMq的服务器

spring:
  rabbitmq:
        addresses: 地址
        username: 用户名
        password: 密码
        virtual-host: 
        cache:
          channel:
            size: 25
        port: 5672

下面是控制带的输出
我是监听消息的,我监听成功了值:hahahahhahahahahhahah。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值