当初始化spring容器后执行某个方法代码如下:
package com.kbmc.dubbo.classbrand.service;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import com.iqcloud.common.ConfigRead.IQCloudConfig;
@Service
public class HeartbeatBagService implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
@Qualifier("pooledConnectionFactory")
private PooledConnectionFactory jmsFactory;
private static final Logger logger = LoggerFactory.getLogger(HeartbeatBagService.class);
@Autowired
private MessageProcessListenerService MessageProcessListenerService;
/*
* 消息生产
*/
private void write() {
Connection connection = null;
Session session = null;
Destination destination = null;
MessageConsumer messageConsumer = null;
try {
connection = jmsFactory.createConnection(); // 通过连接工程获取连接
// connection = connectionFactory.createConnection();
connection.start(); // 启动连接
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 创建session
destination = session.createQueue("C2S_Brand_Msg"); // 消息队列
messageConsumer = session.createConsumer(destination); // 创建消息生产者
System.out.println("K100");
messageConsumer.setMessageListener(MessageProcessListenerService);
/*
* while (true) {
* System.out.println("接收消息================================");
* TextMessage textMessage = (TextMessage)
* messageConsumer.receive(100000); if (textMessage != null){
* System.out.println("收到消息:" + textMessage.getText()); }else{
* break; } }
*/
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// if (connection != null){
// try {
// connection.close();
// } catch (JMSException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
String enabledValue = IQCloudConfig.getParamValueNotOS("activemq", "activeMq.enabled");
logger.info("enabledValue---------------值" + enabledValue);
try {
int iEnabledValue = Integer.valueOf(enabledValue);
if (1 == iEnabledValue) {
write();
}
} catch (Exception e) {
// TODO: handle exception
write();
}
}
}
}
加载完执行:onApplicationEvent方法