新手学习RabbitMQ


1.提示使用springMVC 可以深度了解RabbitMQ的各种配置,强烈推荐使用springMVC+maven 进行项目搭建。
步骤一:下载依赖包。

步骤一:下载依赖包

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>
      <dependency>
          <groupId>com.rabbitmq</groupId>
          <artifactId>amqp-client</artifactId>
          <version>3.5.1</version>
      </dependency>
      <dependency>
          <groupId>org.springframework.amqp</groupId>
          <artifactId>spring-rabbit</artifactId>
          <version>1.4.5.RELEASE</version>
      </dependency>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
<dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>javax.servlet.jsp-api</artifactId>
  <version>2.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.5</version>
</dependency>

第二步:配置springMVC的配置项application-springMVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
          http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 配置扫描的包 -->
    <context:component-scan base-package="com.heping.*" />
    <!-- 开启AOP注解配置,支持切面,通知,切入点注解标记 -->
    <aop:aspectj-autoproxy proxy-target-class="true" ></aop:aspectj-autoproxy>

    <!-- 注册HandlerMapper、HandlerAdapter两个映射类 -->
    <mvc:annotation-driven />

    <!-- 访问静态资源 -->
    <mvc:default-servlet-handler />

    <!-- 视图解析器 -->
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--读取properties文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:mq.properties</value>
            </list>
        </property>
    </bean>
     <!--配置mq-->
    <import resource="application-mq.xml"/>
</beans>

第三步 配置MQ的基本配置 mq.properties

请记住MQ的端口号为5672 ,而RabbitMQ Management的端口号是:15672

mq.host=127.0.0.1
mq.username=heping
mq.password=heping
mq.port=5672

第四步 配置MQ 交换机,队列等配置 application-mq.xml

基本信息我都有写注释,不清楚的可以百度一下哦。

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/rabbit
    http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd" >
    <description>rabbitmq 连接配置文件</description>

    <!--配置连接-->
    <rabbit:connection-factory id="connectionFactory" host="${mq.host}" username="${mq.username}" password="${mq.password}" port="${mq.port}"/>
    <rabbit:admin connection-factory="connectionFactory"/>
    <!--模板配置   exchange 表示为交换机 id="template" 对应的是 生产者的模板-->
    <rabbit:template exchange="heping" id="DirectTemplate" connection-factory="connectionFactory" message-converter="jsonMessageConverter"/>
    <rabbit:template exchange="heping-1" id="TopicTemplate" connection-factory="connectionFactory" message-converter="jsonMessageConverter"/>
    <rabbit:template exchange="heping-2" id="FanoutTemplate" connection-factory="connectionFactory" message-converter="jsonMessageConverter"/>


     <!--消息对象json转换类-->
    <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"/>



    <!--durable:是否持久化 exclusive:仅创建者可以使用的私有队列 断开后自动删除 auto_delete:所有消费客户端断开后 是否自动删除队列-->
    <!--申明队列-->
    <rabbit:queue id="order" name="order" durable="true" auto-delete="false" exclusive="false"/>
    <rabbit:queue id="mail" name="mail" durable="true" auto-delete="false" exclusive="false"/>
    <rabbit:queue id="message" name="message" durable="true" auto-delete="false" exclusive="false"/>

    <!--rabbit:direct-exchange:定义exchange模式为direct,意思就是消息与一个特定的路由键完全符合才能转发-->
    <!--rabbit:binging 设置消息queue匹配的key-->
    <rabbit:direct-exchange name="heping" durable="true" auto-delete="false" id="heping">
        <rabbit:bindings>
            <rabbit:binding queue="order" key="order"/>
            <!--<rabbit:binding queue="mail" key="mail"/>-->
        </rabbit:bindings>
    </rabbit:direct-exchange>

    <!--topic-exchange:定义exchange模式为topic ,意思就是消息与一个特定的路由键可以通过pattern 进行匹配 (#),可以匹配一个或多个字符 -->
    <!--(*)可以只能匹配一个字符 -->
    <rabbit:topic-exchange name="heping-1" id="heping-1" auto-delete="false" durable="true">
        <rabbit:bindings>
            <rabbit:binding queue="mail" pattern="heping.#"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>

    <!--fanout-exchange:定义exchange模式为fanout,意思无需匹配-->
    <rabbit:fanout-exchange name="heping-2" durable="true" auto-delete="false" id="heping-2">
        <rabbit:bindings>
            <rabbit:binding queue="message"></rabbit:binding>
        </rabbit:bindings>
    </rabbit:fanout-exchange>

第五步 创建生产者

@Service
public class MQProducerImpl{
    private final static Logger LOGGER = Logger.getLogger(MQProducerImpl.class);
    //这些模板在配置文件已经进行声明了 
    @Resource
    private AmqpTemplate DirectTemplate;
    @Resource
    private AmqpTemplate TopicTemplate;
    @Resource
    private AmqpTemplate FanoutTemplate;


    /**
     * direct 转发 匹配一个字符
     * @param ququekey, object
     * @return void
     * @version 1.0 2019/3/31 09:16 by peace (ping.he04@ucarinc.com) 创建
     */
    @Override
    public void setDataToQueueForDirect(String ququekey,Object object){

        try{
            DirectTemplate.convertAndSend(ququekey,object);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *topic 转发 * 只能匹配一个字符 # 匹配一个或多个字符
     * @param ququeKey, object
     * @return void
     * @version 1.0 2019/3/31 09:16 by peace (ping.he04@ucarinc.com) 创建
     */
    @Override
    public void setDataToQueueForTopic(String ququeKey,Object object){

        try {
            TopicTemplate.convertAndSend(ququeKey,object);
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }
    /**
     *fanout 无需匹配
     * @param object
     * @return void
     * @version 1.0 2019/3/31 09:46 by peace (ping.he04@ucarinc.com) 创建
     */
    @Override
    public void setDataToQueueForFanOut(Object object) {

        try {
            FanoutTemplate.convertAndSend(object);
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }
}

第六步 消费者

这里可以了解一下消费机制 ack RabbitMQ入门教程(十二):消息确认Ack
public class mailListener implements ChannelAwareMessageListener {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
String str = new String(message.getBody(), “UTF-8”);
//消息的标识,false只确认当前一个消息都到,true 确认consumer获取到的消息
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
System.out.println(str);
}
}

第七步 测试类

@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/dispatcher-servlet.xml"})
public class test {
    @Resource
    MQProducerImpl mqProducer;

    @Test
    public void send(){
    mqProducer.setDataToQueueForDirect("mail","HELLO WORLD FROM FUTURE");
    mqProducer.setDataToQueueForTopic("heping.heping","HELLO WORLD FROM FUTURE FOR ME");
    mqProducer.setDataToQueueForFanOut("success");

}
}

检查:可以在RabbitMQ Management上进行检查


在这里插入图片描述
第一次写blog ,不足的地方可以提一下意见,谢谢大家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值