ActiveMQ的发布订阅在 SpringBoot 项目中使用


 

 

 完整版配置(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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.8.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.microStationCom</groupId>
	<artifactId>WebApi</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>WebApi</name>
	<!-- springboot 打war包。 默认打包方式为 jar , 这里修改为war -->
 
<!--	<packaging>war</packaging>-->
	<!-- -->
    <packaging>jar</packaging>
	<description>microStationCom WebApi</description>
	<properties>
		<java.version>1.8</java.version>
		<tencent.qcloudsms.version>3.1.298</tencent.qcloudsms.version>
		<pagehelper.version>5.0.3</pagehelper.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<!--最终打成war包,排除内置的tomcat
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-tomcat</artifactId>
				</exclusion>
			</exclusions>
			-->
		</dependency>
 
		<!-- reids -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<!-- 不依赖Redis的异步客户端lettuce -->
			<exclusions>
				<exclusion>
					<groupId>io.lettuce</groupId>
					<artifactId>lettuce-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
 
		<!-- Jedis客户端依赖,默认版本: jedis = 2.9.3 , commons-pool2 = 2.6.2 -->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.3</version>
		</dependency>
 
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>sqljdbc4</artifactId>
			<version>4.0</version>
			<scope>runtime</scope>
		</dependency>
 
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.10</version>
		</dependency>
 
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
		</dependency>
 
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
 
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- mybatis plus 代码生成器 -->
		<!--mybatis plus-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.4.0</version>
		</dependency>
 
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.0</version>
		</dependency>
 
		<!--MyBatis的PageHelper插件-->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>${pagehelper.version}</version>
		</dependency>
 
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
			<version>3.1.0</version>
		</dependency>
 
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.28</version>
		</dependency>
 
 
		<dependency>
			<groupId>com.github.davidfantasy</groupId>
			<artifactId>mybatis-plus-generator-ui</artifactId>
			<version>1.4.5</version>
			<scope>test</scope>
		</dependency>
 
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>
 
 
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
			<scope>runtime</scope>
		</dependency>
 
 
		<!-- swagger -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>
 
		<!-- 使用httpclient需要的maven依赖  -->
		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4.9</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>
		<!-- logging日志 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</dependency>
 
		<!--添加servlet-api的依赖,用来打war包  -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<scope>provided</scope>
		</dependency>
 
		<!-- jstl -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
 
		<!-- 引入JWT -->
		<dependency>
			<groupId>com.auth0</groupId>
			<artifactId>java-jwt</artifactId>
			<version>3.4.1</version>
		</dependency>
 
		<!-- 腾讯云短信功能 -->
		<dependency>
			<groupId>com.tencentcloudapi</groupId>
			<artifactId>tencentcloud-sdk-java</artifactId>
			<version>3.1.298</version>
		</dependency>
 
		<dependency>
			<groupId>com.github.qcloudsms</groupId>
			<artifactId>qcloudsms</artifactId>
			<version>1.0.6</version>
		</dependency>
 
	</dependencies>
 
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<fork>false</fork>
				</configuration>
			</plugin>
 
		</plugins>
	</build>
	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<releases>
				<enabled>false</enabled>
			</releases>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
		<pluginRepository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<releases>
				<enabled>false</enabled>
			</releases>
		</pluginRepository>
	</pluginRepositories>
 
</project>

application.properties

# 使用配置文件
spring.profiles.active=dev

#调试模式
# 1、在application.properties文件添加 debug=true
# 2、
debug=true


# Redis 配置
spring.redis.database=0
spring.redis.host=192.168.0.198
spring.redis.port=6379
spring.redis.password=123456
spring.redis.timeout=6000
spring.redis.jedis.pool.min-idle=20
# 最大空闲数,数据库连接的最大空闲时间。超过空闲数量,数据库连接将被标记为不可用,然后被释放。设为0表示无限制
spring.redis.jedis.pool.max-idle=100
##jedis的最大活跃连接数设为0表示无限制
spring.redis.jedis.pool.max-active=500
#最大等待时间:单位ms
#jedis池没有连接对象返回时,等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。
#如果超过等待时间,则直接抛出JedisConnectionException
spring.redis.jedis.pool.max-wait=60000


# ActiveMQ 配置
# ActiveMQ 地址
spring.activemq.broker-url=tcp://192.168.0.123:61616
# 配置用户名和密码
spring.activemq.user=admin
spring.activemq.password=admin
# 是否使用发布订阅模式,默认为 false ,即用的是点对点的模式
spring.jms.pub-sub-domain=true
# 默认目的地址
spring.jms.template.default-destination=AlarmFlow
# 是否启用连接池
spring.activemq.pool.enabled=true
# 连接池最大连接数配置
spring.activemq.pool.max-connections=50
ActiveMqConfig 配置类: ActiveMqConfig.java
package com.microStationCom.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;

import javax.jms.Queue;
import javax.jms.Topic;

@Configuration
public class ActiveMqConfig {

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

    @Value("${spring.activemq.broker-url}")
    private String url;

    @Value("${spring.activemq.user}")
    private String user;

    @Value("${spring.activemq.password}")
    private String password;

    @Value("${spring.jms.template.default-destination}")
    private String topicName;

    @Bean
    public Queue queue() {
        return new ActiveMQQueue("queue");
    }

    @Bean
    public Topic topic() {
        return new ActiveMQTopic(topicName);
    }

    @Bean
    public ActiveMQConnectionFactory connectionFactory() {

        logger.info("============== activeMQ 连接池注入 开始 ===============");
        logger.info("username:{}", this.user);
        logger.info("password:{}", this.password);
        logger.info("activemq_url:{}", this.url);
        logger.info("============== activeMQ 连接池注入 结束 ===============");

        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(this.user, this.password, this.url);
        //10个最大线程
        activeMQConnectionFactory.setMaxThreadPoolSize(100);
        return activeMQConnectionFactory;
    }

    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ActiveMQConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setConnectionFactory(connectionFactory);
        return bean;
    }

    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ActiveMQConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setPubSubDomain(true);
        bean.setConnectionFactory(connectionFactory);
        return bean;
    }

}

添加消息发送、监听(发布订阅)功能的类:

接口:ActiveMqService.java

package com.microStationCom.service;

//ActiveMQ 服务接口
public interface ActiveMqService {

    //发送消息
    public void sendMsg(String message);
    //接收消息
    public void receiveMsg(String message) ;

}

实现类:ActiveMqServiceImpl.java

package com.microStationCom.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.microStationCom.config.ActiveMqConfig;
import com.microStationCom.entity.activemq.AlarmFlowContent;
import com.microStationCom.entity.activemq.Alarminfo;
import com.microStationCom.entity.activemq.Cdd;
import com.microStationCom.service.ActiveMqService;
import com.microStationCom.service.AlarmFlowbakService;
import com.microStationCom.to.AlarmData;
import com.microStationCom.util.RedisCacheUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ActiveMqServiceImpl implements ActiveMqService {

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

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private AlarmFlowbakService alarmFlowbakService;

    @Override
    /**
     * activeMq 发送端
     * 当前项目不需要发送端
     */
    public void sendMsg(String message) {
//        System.out.println("发送消息 【" + message + "】") ;
//        jmsTemplate . convertAndSend(message);
        //自定义发送地址
        //jmsTemplate.convertAndSend (” your- destination ”, message);

    }

    @Override
    //使用注解,监听地址发过来的消息
    @JmsListener(destination = "${spring.jms.template.default-destination}")
    public void receiveMsg(String message) {

        try {
            //解析警情调派内容
            if (!StringUtils.isEmpty(message) && message.contains("alarmDispatch")){

                logger.info("处理警情调派消息:" + message);
//                JSONObject jsonObject = JSONObject.fromObject(message);
//                AlarmFlowContent alarmFlowContent = (AlarmFlowContent) JSONObject.toBean(jsonObject , AlarmFlowContent.class);
                AlarmFlowContent alarmFlowContent = JSON.parseObject(message , AlarmFlowContent.class);
                if (null != alarmFlowContent.getMsgcontent()
                        && null != alarmFlowContent.getMsgcontent().getAlarminfo()
                        && null != alarmFlowContent.getMsgcontent().getCdd() ){
                    Alarminfo alarminfo = alarmFlowContent.getMsgcontent().getAlarminfo();
                    Cdd cdd = alarmFlowContent.getMsgcontent().getCdd();
                    if ("0".equals(cdd.getDpbs()))
                    {
                        logger.info("处理警情调派消息: --------------- 本次处理开始 , 消息时间 {} --------------- ",alarmFlowContent.getMsgsendtime());
                        logger.info("处理警情调派消息: ---  灾害地址:{} , 警情id:{} , 报警时间:{} , 立案时间:{} , 出动时间:{} , 调派单位id:{} --- ",
                                new Object[]{ alarminfo.getZhdd() , alarminfo.getAlarmid() , alarminfo.getBjsj() , alarminfo.getLasj() , cdd.getCdsj() , cdd.getJsdwdm()
                        });
                        List<AlarmData> list = alarmFlowbakService.GetAlarmData2Redis(alarminfo.getAlarmid() , cdd.getJsdwdm());
                        if (null != list && list.size() > 0){
                            String key = RedisCacheUtils.KEY_ALARM_GROUPID_PREFIX + cdd.getJsdwdm();
                            RedisCacheUtils.set(key , JSONObject.toJSONString(list) , RedisCacheUtils.KEY_ALARM_TIMEOUT);
                            logger.info("处理警情调派消息: ---  将警情数据写入Redis缓存 ... --- ");
                        }else{
                            logger.info("处理警情调派消息: ---  警情数据无法写入Redis缓存!!! ... --- ");
                        }
                        logger.info("处理警情调派消息: --------------- 本次处理结束 , 消息时间 {} --------------- ",alarmFlowContent.getMsgsendtime());
                    }else{
                        logger.info("处理警情调派消息: --------------- 该警情非微站调派记录不处理 {} , 调派标识 {} --------------- " , alarminfo.getAlarmid() , cdd.getDpbs());
                    }
                }else{
                    logger.info("处理警情调派消息: --------------- 当前数据不包含警情或车辆调派信息不处理!!! --------------- ");
                }

            }
        } catch (Exception ex) {

            ex.printStackTrace();
            logger.error("处理警情调派消息: 处理activeMq消息异常," + ex.getMessage());
        } finally {

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值