rabbitmq集成spring的xml配置和java代码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tanqian351/article/details/86525339

RabbitMQ官方支持以下五种队列类型。

队列名称 队列模型 适用
简单队列
工作队列
发布/订阅模式
路由模式
主题模式

 

使用依赖:

<!-- https://mvnrepository.com/artifact/org.springframework.amqp/spring-rabbit -->
<dependency>
    <groupId>org.springframework.amqp</groupId>
    <artifactId>spring-rabbit</artifactId>
    <version>1.7.12.RELEASE</version>
</dependency>

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:rabbit="http://www.springframework.org/schema/rabbit"
       xmlns:context="http://www.springframework.org/schema/context"
       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-4.2.xsd
                             http://www.springframework.org/schema/rabbit
                             http://www.springframework.org/schema/rabbit/spring-rabbit-1.7.xsd">

    <context:property-placeholder location="classpath:config.properties"/>

    <!--配置connection-factory,指定连接rabbit server参数 -->
    <rabbit:connection-factory id="connectionFactory" host="${rabbit.mq.host}" username="${rabbit.mq.username}"
                               password="${rabbit.mq.password}" port="${rabbit.mq.port}"/>
    <!--通过指定下面的admin信息,当前producer中的exchange和queue会在rabbitmq服务器上自动生成 -->
    <rabbit:admin id="connectAdmin" connection-factory="connectionFactory"/>

    <!-- 消息消费者 begin-->

    <!-- 定义消费者实现类 begin-->
    <bean id="mdmDataHandleService" class="com.fsl.lcp.mq.service.impl.MdmDataHandleServiceImpl"/>
    <!-- 定义消费者实现类 end -->

    <!-- 定义消费者,并根据消息类型,绑定实现类 -->
    <bean id="rabbitMqReceiver" class="com.fsl.lcp.mq.listener.RabbitMqReceiver">
        <property name="serviceBeanMap">
            <map>
                <entry key="test" value-ref="mdmDataHandleService"/>
            </map>
        </property>
    </bean>
    <!--定义queue -->
    <rabbit:queue name="${rabbit.mq.queue}" durable="true" auto-delete="false" exclusive="false"
                  declared-by="connectAdmin"/>
    <!-- queue litener 观察 监听模式 当有消息到达时会通知监听在对应的队列上的监听对象 -->
    <rabbit:listener-container connection-factory="connectionFactory">
        <rabbit:listener queues="${rabbit.mq.queue}" ref="rabbitMqReceiver"/>
    </rabbit:listener-container>
    <!-- 消息消费者 end-->

    <!-- 消息生产者 begin-->
    <bean class="com.fsl.lcp.mq.producer.RabbitMqProducer"></bean>
    <!--定义rabbit template用于数据的发送 -->
    <rabbit:template id="rabbitMqTemplate" connection-factory="connectionFactory"/>
    <!-- 消息生产者 end-->

</beans>





config.properties配置:

#rabbitmq   rabbitmq.open-->Y/N
rabbitmq.open=Y
rabbit.mq.host=172.16.20.121
rabbit.mq.port=5672
rabbit.mq.username=fsl
rabbit.mq.password=fsl
rabbit.mq.queue=queue.portal.default

java代码--mq接收者--RabbitMqReceiver.java

import java.util.Map;

import com.fsl.lcp.mq.service.MqHandleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

/**
 * 〈rabbitmq的消费者〉.
 *
 * @author tanqian
 * @create 2019/1/2
 */
public class RabbitMqReceiver implements MessageListener {

    private Logger log = LoggerFactory.getLogger(RabbitMqReceiver.class);

    private Map<String, MqHandleService> serviceBeanMap;

    @Override
    public void onMessage(Message message) {

        try {
            String str = new String(message.getBody(), "utf-8");
            log.info(" receive body------->:" + str);
            //处理消息
            String type = "test";
            serviceBeanMap.get(type).handleMqData(message);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("error:" + e.getMessage());
        }
    }

    public Map<String, MqHandleService> getServiceBeanMap() {
        return serviceBeanMap;
    }

    public void setServiceBeanMap(Map<String, MqHandleService> serviceBeanMap) {
        this.serviceBeanMap = serviceBeanMap;
    }


}

java代码--mq消息处理者公共接口类--MqHandleService.java

import org.springframework.amqp.core.Message;

/**
 * 处理mq消息的接口类.
 *
 * @author tanqian
 * @date 2019/01/11
 */
public interface MqHandleService {

    /**
     * 处理mq过来的数据.
     */
    void handleMqData(Message message);

}

java代码--mq消息处理者实现类--MdmDataHandleServiceImpl.java


import com.fsl.lcp.mq.service.MqHandleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
 
/**
 * 处理mdm的mq消息的实现类.
 *
 * @author tanqian
 * @date 2019/01/07
 */
@Transactional(rollbackFor = Exception.class)
public class MdmDataHandleServiceImpl implements MqHandleService {
 
    private Logger log = LoggerFactory.getLogger(MdmDataHandleServiceImpl.class);
 
    @Override
    public void handleMqData(Message message) {
        try {
            //处理消息
            String str = new String(message.getBody(), "utf-8");
            log.info(" receive body------->:" + str);
        } catch (Exception e) {
            log.error("Exception------->:" + e.getMessage());
        }
    }
}

java代码--mq消息发送者类--RabbitMqProducer.java,其中rabbitMqTemplate可以直接通过注解获取

import java.io.IOException;

import com.hand.hap.core.components.ApplicationContextHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;

/**
 * rabbitmq消息的生产者.
 *
 * @author tanqian
 * @date 2019/01/11
 */
public class RabbitMqProducer {

    private Logger log = LoggerFactory.getLogger(RabbitMqProducer.class);

    private ApplicationContext beanFactory;

    @Value("${rabbitmq.open}")
    private String rabbitmqOpen;

    //    @Resource(name = "rabbitMqTemplate")
    private AmqpTemplate rabbitMqTemplate;

    public void sendMessage(String exchange, String routingKey, Object message) throws IOException {
        //初始化bean
        this.loadService();
        log.info("to send message:{}", message);
        rabbitMqTemplate.convertAndSend(exchange, routingKey, message);
    }

    /**
     * 加载注入的bean.
     */
    private void loadService() {
        if (null == beanFactory) {
            beanFactory = ApplicationContextHelper.getApplicationContext();
            if (null == beanFactory) {
                return;
            }
        }
        if (rabbitMqTemplate == null && rabbitmqOpen.equals("Y")) {
            rabbitMqTemplate = (AmqpTemplate) beanFactory.getBean("rabbitMqTemplate");
        }

    }
}

文档参考:

中文文档:http://rabbitmq.mr-ping.com/

官方文档:http://www.rabbitmq.com/getstarted.html

 

 

猜你喜欢

转载自blog.csdn.net/tanqian351/article/details/86525339
0条评论
添加一条新回复