RabbitMQ的广播模式(fanout)在(基于xml配置)项目中使用

news2025/1/14 17:55:45

项目结构

 

添加相关的jar包: pom.xml

<?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>com.zgp.alarm</groupId>
    <artifactId>AlarmStatusManageNew</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <junit.version>4.11</junit.version>
        <aspectj.version>1.6.8</aspectj.version>
        <spring.version>5.0.7.RELEASE</spring.version>
        <servlet.version>3.1.0</servlet.version>
        <jsp.version>2.3.1</jsp.version>
        <jstl.version>1.2</jstl.version>
        <slf4j.version>1.7.12</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
        <mysql.version>5.1.6</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
        <mybatis-spring.version>1.3.1</mybatis-spring.version>
        <pagehelper.version>5.0.3</pagehelper.version>
        <sqlserver.version>4.0</sqlserver.version>
        <druid.version>1.1.9</druid.version>
        <jackson.version>2.9.5</jackson.version>
        <!-- 整合RabbitMQ -->
        <rabbitmq.version>2.1.2.RELEASE</rabbitmq.version>
        <!-- apache 公共资源包 -->

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
        <!-- 添加Spring支持 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- spring redis配置: 注意 spring5以上需要配置 spring-data-redis 2.0 -->
        <!-- https://docs.spring.io/spring-data/redis/docs/2.2.12.RELEASE/reference/html/#new-features  -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

        <!-- 添加Servlet Api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- 添加jtl支持 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>

        <!-- 添加日志支持 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!-- 添加mybatis支持 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring.version}</version>
        </dependency>

        <!--MyBatis的PageHelper插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>

        <!-- sqlserver驱动 -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>${sqlserver.version}</version>
        </dependency>

        <!-- 添加连接池druid支持 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <!-- apache公共包 -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- 文件上传 commons-fileupload 、commons-io -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>


        <!--Jackson required包-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- 配置 quartz 定时器 -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.0</version>
        </dependency>

        <!-- 使用httpclient需要的maven依赖  -->
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>


        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.4</version>
        </dependency>

        <!-- **********************************  版本冲突问题  ************************************ -->
        <!--
           activemq-all-5.14.3 与 spring 5.X 冲突
           解决办法
           1、activemq-all-5.14.3 与 spring 4.2.4 冲突
           2、spring5.X 、activemq-all-5.11.1(没有spring依赖)、javax.jms-api
        -->
        <!-- 配置activemq -->
        <!-- https://mvnrepository.com/artifact/org.apache.activemq/activemq-all -->
<!--        <dependency>-->
<!--            <groupId>org.apache.activemq</groupId>-->
<!--            <artifactId>activemq-all</artifactId>-->
<!--            <version>5.11.1</version>-->
<!--        </dependency>-->
<!--        &lt;!&ndash; https://mvnrepository.com/artifact/javax.jms/javax.jms-api &ndash;&gt;-->
<!--        <dependency>-->
<!--            <groupId>javax.jms</groupId>-->
<!--            <artifactId>javax.jms-api</artifactId>-->
<!--            <version>2.0.1</version>-->
<!--        </dependency>-->

        <!-- RabbitMQ -->
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit</artifactId>
            <version>${rabbitmq.version}</version>
        </dependency>


        <!-- APP消息推送工具: 个推 -->
        <dependency>
            <groupId>com.getui.push</groupId>
            <artifactId>restful-sdk</artifactId>
            <version>1.0.0.0</version>
        </dependency>


        <!-- ehcache 相关依赖
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>2.8.2</version>
    </dependency>
    -->

        <!-- 添加shiro支持
        <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-core</artifactId>
          <version>1.3.2</version>
        </dependency>
        <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-web</artifactId>
          <version>1.3.2</version>
        </dependency>
        <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-spring</artifactId>
          <version>1.3.2</version>
        </dependency>
         -->

        <!-- Shiro框架中配置的ehcache
        <dependency>
          <groupId>net.sf.ehcache</groupId>
          <artifactId>ehcache-core</artifactId>
          <version>2.6.11</version>
        </dependency>
        <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-ehcache</artifactId>
          <version>1.3.2</version>
        </dependency>
        -->

        <!-- jdbc驱动包
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
          -->
        <!-- 添加百度编辑器ueditor支持
        <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.1</version>
        </dependency>
     -->
        <!-- json-lib 依赖包
        <dependency>
          <groupId>net.sf.ezmorph</groupId>
          <artifactId>ezmorph</artifactId>
          <version>1.0.6</version>
        </dependency>
    -->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>


    </dependencies>

    <build>
        <finalName>AlarmStatusManage</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.3.2</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
                <!-- 配置tomcat -->
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <port>8080</port>
                        <path>/AlarmStatusManage</path>
                        <uriEncoding>UTF-8</uriEncoding>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>




</project>

配置文件及java类

1、config.properties、log4j.properties

config.properties

#RabbitMQ Settings
# rabbit ip   
rabbit.server=192.168.0.103
# rabbit 端口
rabbit.port=5672
# virtual-host  默认为 /
rabbit.vhost=/
# rabbit 用户名
rabbit.username=admin
# rabbit 密码
rabbit.password=admin
# 队列名称
rabbit.fanoutQueue=fanoutQueue
# Exchange名称 
rabbit.fanoutExchange=fanoutExchange

# jdbc connection
jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://192.168.0.103:1433;DatabaseName=alarm
jdbc.username=sa
jdbc.password=123456

onfig.properties

log4j.rootLogger=INFO,ERROR,Console

#Console #输出到控制台
log4j.appender.Console = org.apache.log4j.ConsoleAppender 
log4j.appender.Console.layout = org.apache.log4j.PatternLayout 
log4j.appender.Console.layout.ConversionPattern = [%-5p][%-22d{yyyy/MM/dd HH:mm:ssS}][%l]%n%m%n 
log4j.appender.Console.Threshold = DEBUG 
log4j.appender.Console.ImmediateFlush = TRUE 
log4j.appender.Console.Target = System.out 


#输出到文件
log4j.appender.logFile = org.apache.log4j.FileAppender 
log4j.appender.logFile.layout = org.apache.log4j.PatternLayout 
log4j.appender.logFile.layout.ConversionPattern = [%-5p][%-22d{yyyy/MM/dd HH:mm:ssS}][%l]%n%m%n 
log4j.appender.logFile.Threshold = DEBUG 
log4j.appender.logFile.ImmediateFlush = TRUE 
log4j.appender.logFile.Append = TRUE 
log4j.appender.logFile.File = ${catalina.base}/logs/AlarmStatus_INFO.log 
log4j.appender.logFile.Encoding= UTF-8 

#按DatePattern输出到文件
log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender 
log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout 
log4j.appender.ERROR.layout.ConversionPattern = [%-5p][%-22d{yyyy/MM/dd HH:mm:ssS}][%l]%n%m%n 
log4j.appender.ERROR.Threshold = ERROR 
log4j.appender.ERROR.ImmediateFlush = TRUE 
log4j.appender.ERROR.Append = TRUE 
log4j.appender.ERROR.File = ${catalina.base}/logs/AlarmStatus_ERROR.log
log4j.appender.ERROR.DatePattern = '_'yyyy-MM-dd'.log'


#设定文件大小输出到文件
log4j.appender.INFO = org.apache.log4j.RollingFileAppender 
log4j.appender.INFO.layout = org.apache.log4j.PatternLayout 
log4j.appender.INFO.layout.ConversionPattern = [%-5p][%-22d{yyyy/MM/dd HH:mm:ssS}][%l]%n%m%n 
log4j.appender.INFO.Threshold = INFO 
log4j.appender.INFO.ImmediateFlush = TRUE 
log4j.appender.INFO.Append = TRUE 
log4j.appender.INFO.File = ${catalina.base}/logs/AlarmStatus_INFO.log
log4j.appender.INFO.MaxFileSize = 20MB 
log4j.appender.INFO.MaxBackupIndex = 10 




2、RabbitMQ配置文件: spring-rabbitmq-server.xml、spring-rabbitmq-client.xml

spring-rabbitmq-server.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/rabbit
 	   http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
 	   http://www.springframework.org/schema/beans
 	   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">



	<!-- rabbitMq 发送端 -->

<!--	<context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true" />-->
	<!-- 配置连接工厂 -->
	<rabbit:connection-factory id="connectionFactory"
							   host="${rabbit.server}"
							   port="${rabbit.port}"
							   username="${rabbit.username}"
							   password="${rabbit.password}"
							   virtual-host="${rabbit.vhost}"
							   publisher-confirms="true"
							   publisher-returns="true"
							   channel-cache-size="5" />

	<!-- 定义mq管理 -->
	<rabbit:admin connection-factory="connectionFactory" />

	<!-- 声明队列 -->
<!--	<rabbit:queue name="queue" auto-declare="true" durable="true" />-->

	<rabbit:queue name="${rabbit.fanoutQueue}" auto-declare="true" durable="true" />


	<!-- 配置广播模式:fanout -->
	<!-- 定义fanout exchange,绑定queue -->
	<rabbit:fanout-exchange name="${rabbit.fanoutExchange}" auto-declare="true" durable="true">
		<rabbit:bindings>
			<rabbit:binding  queue="${rabbit.fanoutQueue}"/>
		</rabbit:bindings>
	</rabbit:fanout-exchange>


	<!-- 定义交换机绑定队列(路由模式)
	<rabbit:direct-exchange name="IExchange" id="IExchange">
		<rabbit:bindings>
			<rabbit:binding queue="queue" key="queuekey" />
		</rabbit:bindings>
	</rabbit:direct-exchange>
	 -->

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

	<!-- 定义模版
	<rabbit:template id="rabbitTemplate"
					 connection-factory="connectionFactory" exchange="${rabbit.fanoutExchange}"
					 message-converter="jsonMessageConverter" />
	-->

	<rabbit:template id="rabbitTemplate"
					 connection-factory="connectionFactory" exchange="${rabbit.fanoutExchange}"
					 />



</beans>

spring-rabbitmq-client.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/rabbit
 	   http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
 	   http://www.springframework.org/schema/beans
 	   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">


<!--	<context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true" />-->

	<!-- 配置连接工厂 -->
	<rabbit:connection-factory id="connectionFactory"
							   host="${rabbit.server}"
							   port="${rabbit.port}"
							   username="${rabbit.username}"
							   password="${rabbit.password}"
							   virtual-host="${rabbit.vhost}"
							   publisher-confirms="true"
							   publisher-returns="true"
							   channel-cache-size="5" />

	<!-- 定义mq管理: 包括队列、交换器等 -->
	<rabbit:admin connection-factory="connectionFactory" />

	<!-- 声明队列 -->
<!--	<rabbit:queue name="queue" auto-declare="true" durable="true" />-->

	<!-- 声明队列,广播模式
	<rabbit:queue name="${rabbit.fanoutQueue}" auto-declare="true" durable="true" />
   -->


	<!-- 定义消费者 -->
	<bean name="queuehandler" class="com.zgp.alarm.rabbitMq.client.RecvHandler" />

	<!-- 定义消费者监听队列 -->
	<rabbit:listener-container
			connection-factory="connectionFactory">
		<rabbit:listener ref="queuehandler" queues="${rabbit.fanoutQueue}" />
	</rabbit:listener-container>

</beans>


 

3、RabbitMQ消息发送端类(消息发布):StatusSchedule.java (主要是(使用)注入 rabbitTemplate 类发送消息、当然也可以注入将rabbitTemplate 类到后台控制器类或工具类中或配置类中等)

package com.zgp.alarm.schedule;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zgp.alarm.bean.*;
import com.zgp.alarm.service.IAlarmStatusService;
import com.zgp.alarm.utils.CommonUtils;
import com.zgp.alarm.utils.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class StatusSchedule {

    private static Logger logger = LoggerFactory.getLogger(StatusSchedule.class);

    private ObjectMapper mapper = new ObjectMapper();

    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IAlarmStatusService alarmStatusService;

    //处理警情接收确认状态
    public void processAlarmStauts() {
        try{
            logger.info("【处理警情接收确认状态】:开始处理......");
            List<AlarmStatus> datalist = alarmStatusService.getAlarmStatus(1);
            if (datalist != null && datalist.size() > 0){
                AlarmStatus updateModel = datalist.get(0);
                for(int i = 0;i < datalist.size();i++){
                    AlarmStatus currentModel = datalist.get(i);
                    MsgContentStatusResult msgContentResult = new MsgContentStatusResult();
                    msgContentResult.setUnitName(currentModel.getUnitName());
                    msgContentResult.setMessageType("1");//消息类型 0:送达 1:确认

                    //消息内容
                    AlarmStatusResult alarmStatusResult = new AlarmStatusResult();
                    alarmStatusResult.setMsgid(RandomUtils.getUUID());//消息ID
                    alarmStatusResult.setMsgsendtime(CommonUtils.getCurrentDateTime());//发送消息时间
                    alarmStatusResult.setMsgreceiver("");
                    alarmStatusResult.setMsgsender("ALARM");//消息发送者(系统)
                    alarmStatusResult.setMsgtype("DPHZ");//调派回执信息
                    alarmStatusResult.setMsgcontent(msgContentResult);//消息体
//                    rabbitTemplate.convertAndSend(alarmStatusResult);

                    rabbitTemplate.convertAndSend(mapper.writeValueAsString(alarmStatusResult));

                    //保存发送记录。
                    AlarmStatusSend statusSend = new AlarmStatusSend(
                            1, 
                            updateModel.getId(),
                            updateModel.getJjdid(),
                            updateModel.getConfirmTime(),
                            alarmStatusResult.getMsgid(),
                            alarmStatusResult.getMsgsendtime(),
                            alarmStatusResult.getMsgsender(),
                            alarmStatusResult.getMsgreceiver(),
                            alarmStatusResult.getMsgtype(),
                            mapper.writeValueAsString(msgContentResult)
                    );
                    Integer saveFlag = alarmStatusService.saveAlarmStatusSend(statusSend);
                    logger.info("【处理警情接收确认状态】:保存状态发送记录表 saveFlag={} , uploadId={} , msgid={} , msgsendtime = {}"
                            , saveFlag , statusSend.getUploadId() , statusSend.getMsgid() ,statusSend.getMsgsendtime());
                }
                //更新记录
                Integer updateFlag = alarmStatusService.updateAlarmStatus(updateModel);
                logger.info("【处理警情接收确认状态】:更新警情接收确认表 updateFlag={} , 当前记录={}", updateFlag , mapper.writeValueAsString(updateModel));
            }else{
                logger.info("【处理警情接收确认状态】:本次没有查询到待发转态记录.....");
            }

            logger.info("【处理警情接收确认状态】:结束处理......");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("【处理警情接收确认状态】:出现异常,异常信息为:{}",e.getMessage());
        }
    }

   

    public RabbitTemplate getRabbitTemplate() {
        return rabbitTemplate;
    }

    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }
}

4、ActiveMQ消息接收端(监听)类(订阅): RecvHandler.java
package com.zgp.alarm.rabbitMq.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zgp.alarm.bean.AlarmStatus;
import com.zgp.alarm.bean.AlarmStatusResult;
import com.zgp.alarm.bean.Response;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

public class RecvHandler implements MessageListener {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void onMessage(Message message) {
        try {
            // msg就是rabbitmq传来的消息,需要的同学自己打印看一眼
            // 使用jackson解析\
            String text = new String(message.getBody());
//            String text2 = mapper.readValue(message.getBody() , String.class);
            System.out.println("接收服务器消息1:" + text);

            AlarmStatusResult response = mapper.readValue(text , AlarmStatusResult.class);
            System.out.println("接收服务器消息2:msgid=" + response.getMsgid() + " , message=");
//            JsonNode jsonData = MAPPER.readTree(message.getBody());
//            System.out.println("我是可爱的小猪,我的id是" + jsonData.get("id").asText() + ",我的名字是" + jsonData.get("name").asText());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

5、spring主配置文件 applicationContext.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!--  配置数据源 SQLServer  -->
    <!--
    <bean id="dataSource"
		class="com.alibaba.druid.pool.DruidDataSource">
		<property name="url" value="jdbc:sqlserver://192.168.0.103:1433;DatabaseName=MicroStation"/>
		<property name="username" value="sa"/>
		<property name="password" value="123456"/>

	</bean>
    -->
    <!--
    <context:property-placeholder location="classpath:jdbc.properties" ignore-resource-not-found="true" ></context:property-placeholder>
    -->

    <!--
	  导入配置文件 config.properties 、redis.properties
	  注意:如果项目中有多个属性文件,要合并在一起加载同一管理。如果分散在不同的配置文件中,只能按文件顺序加载第一个配置文件中的属性文件。
	  <context:property-placeholder location="classpath*:config.properties"></context:property-placeholder>
	-->
    <context:property-placeholder location="classpath*:config.properties"></context:property-placeholder>


    <!-- 配置数据库 alarm -->
    <bean id="dataSource"
		class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
        <!-- 配置初始化大小、bai最小、最大 -->
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <property name="maxActive" value="20" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
        <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
        <property name="filters" value="stat" />
	</bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mapperLocations" value="classpath:/mapper/*.xml"></property>
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>

        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=sqlserver2012
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
	</bean>
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.zgp.alarm.dao"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>


    <!-- 开启注解: 自动扫描 -->
    <context:annotation-config></context:annotation-config>

    <!-- 配置事务(注解方式) -->
    <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
    <!-- base-package 如果多个,用“,”分隔  -->
    <context:component-scan base-package="com.zgp.alarm.service">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>


    <!-- 定义事务   -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>


    <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务  -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    <!-- MyBatis end -->

   <!-- -->
   <context:component-scan base-package="com.zgp.alarm.service.impl" />
   <context:component-scan base-package="com.zgp.alarm.dao" />



    <!-- rabbitmq 服务端  -->
    <import resource="classpath:spring-rabbitmq-server.xml" />
    <!-- rabbitmq 客户端测试 -->
    <import resource="classpath:spring-rabbitmq-client.xml" />


    <!-- 处理警情接收确认状态  -->
    <!-- 每分钟执行一次 -->
<!--    <import resource="classpath:applicationContext-job-faultInfo.xml" />-->



</beans>

6、定时任务配置文件:applicationContext-job-faultInfo.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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">


    <bean id="statusSchedule" class="com.zgp.alarm.schedule.StatusSchedule">
        <property name="rabbitTemplate" ref="rabbitTemplate" ></property>
    </bean>

    <!-- 处理警情接收确认状态: 每分钟执行一次 -->
    <bean id="alarmStautsZzdJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"
        depends-on="rabbitTemplate">
        <property name="targetObject" ref="statusSchedule" />
        <property name="targetMethod" value="processAlarmStautsZzd" />
        <property name="concurrent" value="false" />
    </bean>
    <bean id="alarmStautsJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="alarmStautsJobDetail" />
        <property name="cronExpression"  >
            <value>0 */1 * * * ?</value>
        </property>
    </bean>


    <!-- 任务调度触发器 -->
    <bean autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" >
        <property name="triggers">
            <list>
                <ref bean="alarmStautsJobTrigger" />
            </list>
        </property>
    </bean>

</beans>

7、mybatis配置文件:mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

	<settings>
		<!-- 配置日志记录工具 -->
		<setting name="logImpl" value="SLF4J"/>

		<!-- 将sql语句打印到控制台 -->
		<setting name="logImpl" value="STDOUT_LOGGING" />

	</settings>
	<!-- 定义别名 -->
	<typeAliases>
		<typeAlias alias="alarmStatus" type="com.zgp.alarm.bean.AlarmStatus"></typeAlias>

		<typeAlias alias="alarmStatusSend" type="com.zgp.alarm.bean.AlarmStatusSend" ></typeAlias>

		<typeAlias alias="msgContentUnitsResult" type="com.zgp.alarm.bean.MsgContentUnitsResult"></typeAlias>

		<typeAlias alias="msgContentCarsResult" type="com.zgp.alarm.bean.MsgContentCarsResult"></typeAlias>



	</typeAliases>

</configuration>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/24374.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

@敏捷组织从业者,开放敏捷架构O-AA™标准考试及认证项目重磅上线!

数字化转型和敏捷转型需同时进行&#xff0c; O-AA™标准更强调组织和文化的转型。 认证项目 重磅发布 发布物资源 标准中文从业认证考试 标准讲师认证培训课程 ALL IN ∨ 开放敏捷架构O-AA™标准采用了基于结果、以产品为中心的方法&#xff0c;使企业能够以灵活和敏捷的…

[ros2实操]1-ros2的安装(ubuntu1804)与运行

参考链接: Recording and playing back data — ROS 2 Documentation: Galactic documentation 使用docker创建了一个ubuntu1804镜像: docker run -it --gpus all \-p 8860:8860 \-v /tmp/.X11-unix:/tmp/.X11-unix \-v /home/lbw/temp_dir:/temp_dir \-e DISPLAYunix$DISPL…

软件测试行业5年经验,薪资不如刚入行的应届生,真是日了狗了,问题究竟出在哪里?

最近公司新招了一位刚入行的应届生&#xff0c;作为组长我深刻体验到新人入行的痛楚&#xff0c;对此我十分照顾他&#xff0c;都是手把手教他公司业务流程。直到15号他工资到账15400元短信提示音响起&#xff0c;我才想起这是多么幼稚的行为&#xff0c;凭什么我在公司待了五年…

实验三 静态路由配置

计算机网络实验实验三 静态路由配置一、实验目的二、实验目的三、实验步骤3.1 连接实验拓扑结构3.2 配置路由器IP地址和掩码3.3 配置PC机IP地址、网关地址3.4 配置路由器的路由表四、思考题实验三 静态路由配置 一、实验目的 掌握手工配置路由表的方法 掌握读懂路由表的能力 …

Charles安装配置

目录 一、工作原理 二、主要功能 三、主要优点&#xff08;对比Fiddler&#xff09; 四、安装与配置 1、安装 2、组件介绍 1&#xff09;主导航栏 2&#xff09;请求栏 3&#xff09;请求数据栏 3、设置 1&#xff09;代理设置 2&#xff09;访问控制 4、客户端设置 …

(C语言)P1002 [NOIP2002 普及组] 过河卒

[NOIP2002 普及组] 过河卒 一、题目描述 棋盘上 AAA 点有一个过河卒&#xff0c;需要走到目标 BBB 点。卒行走的规则&#xff1a;可以向下、或者向右。同时在棋盘上 CCC 点有一个对方的马&#xff0c;该马所在的点和所有跳跃一步可达的点称为对方马的控制点。因此称之为“马拦…

Redis实战——短信登录

目录 1 基于Seesion实现短信登录 1.1 发送短信验证码 1.2 登录功能 2 使用Redis进行短信验证码校验登录 2.1 Seesion方法存在的问题 2.2 发送短信验证码 2.3 验证码校验及登录功能 3.拦截器优化 1 基于Seesion实现短信登录 1.1 发送短信验证码 发送验证码请求路径 /u…

2、skywalking-安装(Docker-Compose方式)

1、服务器环境介绍 两台服务器均为Centos7.6 172.16.128.129 vm1 装载skywalking(采用es作为数据库) 172.16.128.130 vm2 项目服务器&#xff0c;然后向vm1集成 2、准备工作 2.1、由于安装skywalking是通过docker-compose方式安装在vm1且项目到时候是直接build成镜像然后发布&a…

行业安全解决方案 | 零售企业如何做好安全建设对抗黑灰产?

随着各行各业信息化、数字化、智能化进程不断加快&#xff0c;零售行业新业态也正在蓬勃发展。然而&#xff0c;随着转型深入推进及业务量的上升&#xff0c;随处可见的安全威胁逐渐成为零售企业的首要难题。 其主要原因在于该类企业一般涵盖大量用户个人数据&#xff0c;当企…

2022,软件测试行业岗位细分,薪资分布

软件测试是个需求多&#xff0c;就业机会大的职业。目前&#xff0c;我国具备软件测试能力的人员数量和市场需求相差巨大&#xff0c;巨大的市场空缺&#xff0c;使软件测试工程师从初级到高级&#xff0c;只需要 1 年甚至更短的时间来完成。所以作为一名软件测试工程师&#x…

图像基础知识、深度学习基础知识以及相关问题

疑难问题总结第一部分&#xff1a;图像基础边缘和轮廓1、图像中&#xff0c;什么是高频域和低频域&#xff1f;2、什么是图像轮廓&#xff0c;什么是图像边缘&#xff1f;第二部分&#xff1a;深度学习第一部分&#xff1a;图像基础 边缘和轮廓 1、图像中&#xff0c;什么是高…

从一座瑞典风机的倒塌看VDI2230用于螺栓连接精确计算的重要性

作者&#xff1a;螺栓设计老张 一、写在前面 引言&#xff1a;在机械行业&#xff0c;螺栓是与轴承、齿轮齐名的三大最主要机械元素&#xff0c;而从应用广泛程度来看&#xff0c;相比于轴承和齿轮是有过之而无不及。无论是机械传动还是机械结构&#xff0c;都离不开螺栓&…

[附源码]Python计算机毕业设计成绩管理与学情分析系统

项目运行 环境配置&#xff1a; Pychram社区版 python3.7.7 Mysql5.7 HBuilderXlist pipNavicat11Djangonodejs。 项目技术&#xff1a; django python Vue 等等组成&#xff0c;B/S模式 pychram管理等等。 环境需要 1.运行环境&#xff1a;最好是python3.7.7&#xff0c;…

WPS—JS宏笔记记录

前言&#xff1a;本方法需要一定的JS基础&#xff0c;这边不会赘述&#xff0c;0基础者可先自学JS 文章目录官方参考文档壹——excel表格篇一、创建新的表格输入内容并保存关闭ThisWorkbook&#xff1a;Application.Path:Workbooks:workbooks.Add:Sheets&#xff1a;自测&#…

OpenCV-Python小应用(五):基于模板匹配的图像拼接

OpenCV-Python小应用&#xff08;五&#xff09;&#xff1a;基于模板匹配的图像拼接前言前提条件实验环境基于模板匹配的图像拼接参考文献前言 本文是个人使用OpenCV-Python的应用案例&#xff0c;由于水平有限&#xff0c;难免出现错漏&#xff0c;敬请批评改正。更多精彩内容…

【微服务】分布式组件 Nacos 结合 Feign 的使用

本文主要介绍如何搭建分布式开发基本环境 一、基本概念 1. 注册中心 在分布式系统中&#xff0c;每一个微服务上线&#xff0c;都需要注册到注册中心。&#xff08;方便服务的远程调用&#xff0c;比如订单想调用商品服务&#xff0c;直接从注册中心获得&#xff09; 对应 Sp…

SpringBoot整合mybatis

SpringBoot整合mybatis 以tb_book表格为例&#xff1a; 第一步&#xff1a;创建新模块&#xff0c;选择Spring初始化&#xff0c;并配置模块相关基础信息 第二步&#xff1a;选择当前模块需要使用的技术集&#xff08;MyBatis、MySQL&#xff09; 或者手工导入对应技术的star…

idea创建纯净的maven项目简单的maven工程

idea创建简单的maven项目一、说在前面二、创建步骤一、说在前面 在学习或者开发中&#xff0c;有时候&#xff0c;我们只想创建一个简单的maven工程&#xff0c;不需要有太多的自带的配置或配置文件&#xff0c;本文结合这一需求&#xff0c;将创建步骤分享给大家&#xff0c;…

Python Selenium unittest+HTMLTestRunner实现 自动化测试及发送测试报告邮件

1、UI测试框架搭建-目录结构 2、 文件介绍 2.1、baseinfo->__init__.py 配置文件定义基础参数 #-*-coding:utf-8-*- #测试用例配置参数base_url "http://xxxxx.com" undirect_username "username" undirect_password "password" direct_…

想知道怎么给图片加贴纸?手把手教你给图片加贴纸

有时候我们在拍摄照片时&#xff0c;会不小心排到一些隐私的东西&#xff0c;这个时候该怎么办呢&#xff1f;可能很多人会先想到使用马赛克涂抹&#xff0c;这个方法确实好&#xff0c;但马赛克在帮我们遮挡的同时&#xff0c;也会影响到图片的整体观感。那我们应该用什么来代…