SSM项目整合rabbitmq

<!--rabbitmq-->
    <dependency>
      <groupId>org.springframework.amqp</groupId>
      <artifactId>spring-rabbit</artifactId>
      <version>2.1.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.16</version>
    </dependency>

properties里面

mq.user=账户
mq.pwd=密码
mq.ip=服务器IP
mq.port=5672
#队列交换机名
exchange=TestExchange
#队列名
routeKey=testQueue

spring-rabbit.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:util="http://www.springframework.org/schema/util"
       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/util
	    http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/rabbit
        http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:rabbitmq.properties" />
    </bean>
    <!--生产者配置  -->
    <!-- rabbitMQ创建连接类 -->
    <bean class="com.mlwy.rabbitmq.RabbitMQ" />
    <bean id="connectionMqFactory"  class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
        <constructor-arg value="localhost" />
        <property name="username" value="${mq.user}" />
        <property name="password" value="${mq.pwd}" />
        <property name="host" value="${mq.ip}" />
        <property name="port" value="${mq.port}" />
    </bean>

    <bean id="rabbitAdmin"  class="org.springframework.amqp.rabbit.core.RabbitAdmin">
        <constructor-arg ref="connectionMqFactory" />
    </bean>

    <!-- 创建rabbitTemplate 消息模板类 生产者 -->
    <bean id="rabbitTemplate"  class="org.springframework.amqp.rabbit.core.RabbitTemplate">
        <property name="replyTimeout" value="50000" />
        <property name="connectionFactory" ref="connectionMqFactory"/>
    </bean>
    <!-- bean 注入 -->
    <bean class="com.mlwy.rabbitmq.SpringUtil" />
    <!-- 消费者配置 -->
    <!-- 创建消息转换器为SimpleMessageConverter -->
    <bean id="serializerMessageConverter"
          class="org.springframework.amqp.support.converter.SimpleMessageConverter"></bean>


    <!-- 设置持久化的队列 -->
    <bean id="queue" class="org.springframework.amqp.core.Queue">
        <constructor-arg index="0" value="${routeKey}"></constructor-arg>
        <constructor-arg index="1" value="true"></constructor-arg>
        <constructor-arg index="2" value="false"></constructor-arg>
        <constructor-arg index="3" value="false"></constructor-arg>
    </bean>

    <!--创建交换器的类型 并持久化 -->
    <bean id="directExchange" class="org.springframework.amqp.core.DirectExchange">
        <constructor-arg index="0" value="${exchange}"></constructor-arg>
        <constructor-arg index="1" value="true"></constructor-arg>
        <constructor-arg index="2" value="false"></constructor-arg>
    </bean>

    <util:map id="arguments"></util:map>


    <!-- 绑定交换器、队列 -->
    <bean id="binding" class="org.springframework.amqp.core.Binding">
        <constructor-arg index="0" value="${routeKey}"></constructor-arg>
        <constructor-arg index="1" value="QUEUE"></constructor-arg>
        <constructor-arg index="2" value="${exchange}"></constructor-arg>
        <constructor-arg index="3" value="${routeKey}"></constructor-arg>
        <constructor-arg index="4" value="#{arguments}"></constructor-arg>
    </bean>


    <!-- 用于接收消息的处理类 消费者类-->
    <bean id="rmqConsumer" class="com.mlwy.rabbitmq.RmqConsumer"></bean>
    <bean id="messageListenerAdapter"
          class="org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter">
        <constructor-arg ref="rmqConsumer" />
        <!--可以指定哪个队列用哪个方法  -->
        <property name="queueOrTagToMethodName">
            <map>
                <entry key="${routeKey}" value="rmqProducerMessage"></entry>
            </map>
        </property>
        <property name="defaultListenerMethod" value="rmqProducerMessage"></property>
        <property name="messageConverter" ref="serializerMessageConverter"></property>
    </bean>

    <!-- 用于消息的监听的容器类SimpleMessageListenerContainer,监听队列 queues可以传多个 -->
    <bean id="listenerContainer"
          class="org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer">
        <property name="queues">
            <list>
                <ref bean="queue"></ref>
            </list>
        </property>
        <property name="connectionFactory" ref="connectionMqFactory"></property>
        <property name="messageListener" ref="messageListenerAdapter"></property>
    </bean>
</beans>

SSM项目整合rabbitmq_第1张图片

<!-- 扫描service -->
	<context:component-scan base-package="com.mlwy.rabbitmq"></context:component-scan>
	<!--rabbitmq配置-->
	<import resource="classpath:spring-rabbit.xml"/>
package com.mlwy.rabbitmq;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import lombok.Data;
@Data
public class RabbitMessage implements Serializable {
    private static final long serialVersionUID = -6487839157908352120L;

    private Class<?>[] paramTypes;// 参数类型
    private String exchange;// 交换器

    private Object[] params;

    private String routeKey;// 路由key

    private String methodName;
    private String beanName;
    public RabbitMessage() {
    }

    public RabbitMessage(String exchange, String routeKey, Object... params) {
        this.params = params;
        this.exchange = exchange;
        this.routeKey = routeKey;
    }

    @SuppressWarnings("rawtypes")
    public RabbitMessage(String exchange, String routeKey,String beanName, String methodName, Object... params) {
        this.params = params;
        this.exchange = exchange;
        this.routeKey = routeKey;
        this.methodName=methodName;
        this.beanName=beanName;
        int len = params.length;
        Class[] clazzArray = new Class[len];
        for (int i = 0; i < len; i++){
            clazzArray[i] = params[i].getClass();
        }
        this.paramTypes = clazzArray;
    }

    public byte[] getSerialBytes() {
        byte[] res = new byte[0];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            oos.close();
            res = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    public Class<?>[] getParamTypes() {
        return paramTypes;
    }

    public void setParamTypes(Class<?>[] paramTypes) {
        this.paramTypes = paramTypes;
    }

    public String getExchange() {
        return exchange;
    }

    public void setExchange(String exchange) {
        this.exchange = exchange;
    }

    public Object[] getParams() {
        return params;
    }

    public void setParams(Object[] params) {
        this.params = params;
    }

    public String getRouteKey() {
        return routeKey;
    }

    public void setRouteKey(String routeKey) {
        this.routeKey = routeKey;
    }

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public String getBeanName() {
        return beanName;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }
}
package com.mlwy.rabbitmq;

import javax.annotation.Resource;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;

public class RabbitMQ {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Value("${exchange}")
    private String exchange;
    @Value("${routeKey}")
    private String routeKey;
    public void pushMessageToMQ(String className, String methodName,Object... param) {
        RabbitMessage  msg=new RabbitMessage(exchange,routeKey,className, methodName, param);
        try {
            rabbitTemplate.convertAndSend(msg.getExchange(), msg.getRouteKey(), msg);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    /**
     * 同步
     */
    public Object pushAndReceiveMessageToMQ(String className, String methodName,Object... param) {
        RabbitMessage  msg=new RabbitMessage(exchange,routeKey,className, methodName, param);
        Object obj=null;
        try {
            obj= rabbitTemplate.convertSendAndReceive(msg.getExchange(), msg.getRouteKey(), msg);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return obj;
    }

}
package com.mlwy.rabbitmq;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;

public class RmqConsumer {
    private static Logger log=Logger.getLogger(RmqConsumer.class);
    public static void rmqProducerMessage(Object object) throws Exception{
        RabbitMessage rabbitMessage=(RabbitMessage) object;
        log.info("从队列里头取出:bean名-"+rabbitMessage.getBeanName()+",方法名:"+rabbitMessage.getMethodName());
        Object o = SpringUtil.getBean(rabbitMessage.getBeanName());
        Class clazz = o.getClass();
        Method m=clazz.getDeclaredMethod(rabbitMessage.getMethodName(), rabbitMessage.getParamTypes());
        m.invoke(o,rabbitMessage.getParams());
    }
    /*public static Object rmqProducerMessage(Object object) throws Exception{
        RabbitMessage rabbitMessage=(RabbitMessage) object;
        log.info("从队列里头取出:bean名-"+rabbitMessage.getBeanName()+",方法名:"+rabbitMessage.getMethodName());
        Object o = SpringUtil.getBean(rabbitMessage.getBeanName());
        Class clazz = o.getClass();
        Method m=clazz.getDeclaredMethod(rabbitMessage.getMethodName(), rabbitMessage.getParamTypes());
        Object invoke = m.invoke(o,rabbitMessage.getParams());
        return 	invoke;
    }*/
}

package com.mlwy.rabbitmq;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringUtil implements ApplicationContextAware {
    // Spring应用上下文环境
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<?> clz) throws BeansException {
        return (T) applicationContext.getBean(clz);
    }
}

SSM项目整合rabbitmq_第2张图片

你可能感兴趣的:(rabbitmq,定时任务,rabbitmq,交换机,队列)