一、传输异常监听实现类
import org.apache.activemq.transport.TransportListener;
import org.apache.log4j.Logger;
import java.io.IOException;
/**
* 消息传输监听
*
* @author Mafly
*/
public class ActiveMQTransportListener implements TransportListener {
private Logger log = Logger.getLogger(ActiveMQTransportListener.class);
/**
* 对消息传输命令进行监控
*
* @param
*/
@Override
public void onCommand(Object o) {
}
/**
* 对监控到的异常进行触发
*
* @param error
*/
@Override
public void onException(IOException error) {
log.error("onException -> 消息服务器连接错误......", error);
}
/**
* 当failover时触发
*/
@Override
public void transportInterupted() {
log.warn("transportInterupted -> 消息服务器连接发生中断...");
//这里就可以状态进行标识了
}
/**
* 监控到failover恢复后进行触发
*/
@Override
public void transportResumed() {
log.info("transportResumed -> 消息服务器连接已恢复...");
//这里就可以进行状态标识了
}
}
二、注册监听
ActiveMQConnectionFactory:方法setTransportListener(new ActiveMQTransportListener())
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
@Configuration
public class JmsTcpConfig {
@Bean(name = "defaultConnectionFactory")
@Primary
public ActiveMQConnectionFactory firstConnectionFactory(
@Value("${spring.default.activemq.brokerUrl}") String brokerUrl,
@Value("${spring.default.activemq.user}") String username,
@Value("${spring.default.activemq.password}") String password) {
return createConnectionFactory(brokerUrl, username, password);
}
public ActiveMQConnectionFactory createConnectionFactory(String brokerUrl, String username, String password) {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
factory.setBrokerURL(brokerUrl);
factory.setUserName(username);
factory.setPassword(password);
factory.setTransportListener(new ActiveMQTransportListener());//监听连接
return factory;
}
@Bean(name = "defaultJmsTemplate")
@Primary
public JmsMessagingTemplate defaultActivemqTemplate(
@Qualifier("defaultConnectionFactory") ActiveMQConnectionFactory connectionFactory) {
JmsMessagingTemplate template = new JmsMessagingTemplate(connectionFactory);
return template;
}
@Bean(name = "defaultJmsListenerContainerFactory")
public JmsListenerContainerFactory defaultFactory(
@Qualifier("defaultConnectionFactory") ActiveMQConnectionFactory connectionFactory) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
return factory;
}
}