springboot+ActiveMQ队列监听

这里写自定义目录标题

package com.nstc.dbp.plus;

import javax.jms.Destination;

import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

import org.apache.activemq.ActiveMQSslConnectionFactory;

import org.apache.activemq.command.ActiveMQQueue;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

import org.springframework.context.annotation.PropertySources;

import org.springframework.jms.listener.DefaultMessageListenerContainer;

import com.icbc.dmqs.des3.Des3;

@Configuration

@PropertySources({ @PropertySource(“classpath:shcpe.properties”), @PropertySource(“classpath:MQReceive.properties”) })

public class MQConfig {

@Value("${RQ_500_NAME}")

private String one;

@Value("${RQ_600_NAME}")

private String two;

@Value("${UseSSL}")

private String UseSSL;

@Value("${AppID}")

private String appID;

@Value("${Password}")

private String password;

@Value("${BrokerUrl}")

private String brokerUrl;

@Value("${ClientID}")

private String clientId;

@Value("${Failover}")

private String Failover;

@Value("${ConnectStrategy}")

private String ConnectStrategy;

@Value("${AckMode}")

private String AckMode;

@Value("${TrustKeyStore}")

private String TrustKeyStore;

@Value("${TrustKeyStorePassword}")

private String TrustKeyStorePassword;

@Autowired

private DbpBean obj;

@Bean

public DefaultMessageListenerContainer listenerContainer() {

DefaultMessageListenerContainer m = new DefaultMessageListenerContainer();

ActiveMQConnectionFactory cf = null;

String connectUrl = getURL();

if (UseSSL.equalsIgnoreCase(“true”)) {

cf = new ActiveMQSslConnectionFactory();

try {

((ActiveMQSslConnectionFactory) cf).setTrustStore(TrustKeyStore);

((ActiveMQSslConnectionFactory) cf).setKeyStorePassword(TrustKeyStorePassword);

} catch (Exception e) {

throw new RuntimeException(e.getMessage());

}

} else {

cf = new ActiveMQConnectionFactory();

}

cf.setBrokerURL(connectUrl);

cf.setUserName(appID);

cf.setPassword(Des3.dec(“ZX71:#AL9sd2=.qx”, password));

cf.setTrustAllPackages(Boolean.TRUE);

if(AckMode.equalsIgnoreCase(“client”)) {

//不设置值,默认自动确认 AUTO_ACKNOWLEDGE

m.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);

}

m.setConnectionFactory(cf);

Destination d = new ActiveMQQueue(one + “,” + two);// *表示通配所有队列名称

m.setDestination(d);

m.setClientId(clientId);

m.setMessageListener(new QueueMessageListener(obj));

return m;

}

private String getURL() {

String connectUrl = “”;

if (UseSSL.equalsIgnoreCase(“true”)) {

connectUrl = spritAddressSSL(brokerUrl);

} else {

connectUrl = spritAddress(this.brokerUrl);

}

if (Failover.equalsIgnoreCase(“true”)) {

connectUrl = “failover:(” + connectUrl + “)”;

}

if (ConnectStrategy.isEmpty()) {

connectUrl = connectUrl + “?” + ConnectStrategy;

}

return connectUrl;

}

public static String spritAddressSSL(String serverAddress) {

String[] adds = serverAddress.split(",");

String ret = “”;

for (int i = 0; i < adds.length; ++i) {

ret = ret + “ssl://” + adds[i] + “:21593,”;

}

ret = ret.substring(0, ret.length() - 1);

return ret;

}

public String spritAddress(String serverAddress) {

String[] adds = serverAddress.split(",");

String ret = “”;

String port = “21591”;

for (int i = 0; i < adds.length; ++i) {

ret = ret + “tcp://” + adds[i] + “:” + port + “,”;

}

ret = ret.substring(0, ret.length() - 1);

return ret;

}

}


package com.nstc.dbp.plus;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

import javax.jms.JMSException;

import javax.jms.Message;

import javax.jms.MessageListener;

import org.apache.activemq.command.ActiveMQMessage;

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import com.icbc.dmqs.dmqs_client.DMQSMessage;

import com.nstc.dbp.plus.util.RandomGUID;

import com.nstc.dbp.plus.util.SchemaValidator;

import com.nstc.util.TextFormat;

public class QueueMessageListener implements MessageListener {

private static Logger logger = LogManager.getLogger(QueueMessageListener.class);

@Override

public void onMessage(Message arg0) {

ActiveMQMessage msg = (ActiveMQMessage) arg0;

if (msg != null) {

try {

DMQSMessage dmsg = new DMQSMessage((ActiveMQMessage) msg);

if(dmsg.text!=null) {

logger.info(“队列信息【{}】,消息类型【{}】,入列时间【{}】,出列时间【{}】,消息内容【{}】”,msg.getDestination(),dmsg.MessageType,TextFormat.formatDate(new Date(msg.getBrokerInTime()), “yyyy-MM-dd HH:mm:ss SSS”),TextFormat.formatDate(new Date(msg.getBrokerOutTime()), “yyyy-MM-dd HH:mm:ss SSS”),dmsg.text);

String message = dmsg.text;

int index=message.indexOf("{H:");

message = message.substring(index);

//System.out.println(message);

String mid = null;

String OrigSender = null;

String OrigSendDate = null;

String MesgID = null;

try {

OrigSender = message.substring(18, 24);

OrigSendDate = message.substring(30, 38);

MesgID = message.substring(64, 84);

} catch (Exception eee) {

logger.error(“报文头格式错误【{}】”,eee.getMessage());

toErrorFile(RandomGUID.getInatance(), message);

msg.acknowledge();

return;

}

mid = OrigSender + OrigSendDate + MesgID;

String head = message.substring(0, 191);

String msgType = head.substring(44, 55);

String url = getClass().getResource("/schemas/down/" + msgType+".xsd").toString();

if(SchemaValidator.valid(message.substring(191), url, obj.getError())) {

toFile(mid, message);

}

}

msg.acknowledge();

} catch (JMSException | IOException e) {

e.printStackTrace();

}

}

}

private DbpBean obj;

public QueueMessageListener(){}

public QueueMessageListener(DbpBean obj){

this.obj=obj;

}

private void toFile(String messageId, String xmlString) throws IOException {

BufferedWriter bw = null;

try {

String dir=obj.getException();

File directory=new File(dir);

if(!directory.exists()){

directory.mkdirs();

}

File f = new File(dir, messageId + “.xml”);

bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), “UTF-8”));

bw.write(xmlString);

} catch (IOException e) {

e.printStackTrace();

throw e;

} finally {

if (bw != null) {

try {

bw.close();

} catch (IOException e) {

}

}

}

}

private void toErrorFile(String messageId, String xmlString) throws IOException {

BufferedWriter bw = null;

try {

SimpleDateFormat dtformat = new SimpleDateFormat(“yyyyMMdd”);

String dir = obj.getError() + “/” + dtformat.format(new Date());

File directory=new File(dir);

if(!directory.exists()){

directory.mkdirs();

}

File f = new File(dir, messageId + “.xml”);

bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), “UTF-8”));

bw.write(xmlString);

} catch (IOException e) {

e.printStackTrace();

throw e;

} finally {

if (bw != null) {

try {

bw.close();

} catch (IOException e) {

}

}

}

}

}


package com.nstc.dbp.plus;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

@Configuration

@PropertySource(“classpath:DBP.properties”)

public class DbpBean {

@Value("${dbp.error}")

private String error;

@Value("${dbp.exception}")

private String exception;

public String getError() {

return error;

}

public void setError(String error) {

this.error = error;

}

public String getException() {

return exception;

}

public void setException(String exception) {

this.exception = exception;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot与ActiveMQ的集成可以实现消息队列的功能。以下是实现步骤: 1. 配置ActiveMQ依赖:在项目的pom.xml文件中添加ActiveMQ的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> ``` 2. 配置ActiveMQ连接信息:在项目的application.properties(或application.yml)文件中配置ActiveMQ的连接信息。 ```properties spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin ``` 3. 创建消息发送者:编写一个消息发送者类,使用JmsTemplate发送消息到ActiveMQ队列。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; @Component public class MessageSender { @Autowired private JmsTemplate jmsTemplate; public void sendMessage(String message) { jmsTemplate.convertAndSend("myQueue", message); } } ``` 4. 创建消息接收者:编写一个消息接收者类,使用@JmsListener注解监听ActiveMQ队列,并处理接收到的消息。 ```java import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; @Component public class MessageReceiver { @JmsListener(destination = "myQueue") public void receiveMessage(String message) { System.out.println("Received message: " + message); // 处理接收到的消息 } } ``` 5. 发送和接收消息:在需要发送消息的地方,通过调用消息发送者的sendMessage方法发送消息;在消息接收者类中,使用@JmsListener注解监听到消息后进行处理。 通过以上步骤,你就可以在Spring Boot应用中使用ActiveMQ实现消息队列的功能了。记得在启动应用之前,确保你已经启动了ActiveMQ服务器。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值