QPID spring 示例

 - 先在pom文件中加入依賴
<dependency>
    <groupId>org.apache.qpid</groupId>
    <artifactId>qpid-client</artifactId>
    <version>0.24</version>
</dependency>

 - spring中配置相應的bean
<bean id="qpidConnectionFactory" class="org.apache.qpid.client.AMQConnectionFactory">
		<constructor-arg value="${jms.config.qpid.url}"/>
	</bean>
	
	<bean id="qpidQueue" class="org.apache.qpid.client.AMQAnyDestination">
		<constructor-arg value="ADDR:${jms.config.qpid.queue}; {create: always}"/>
	</bean>
	
	<bean id="qpidJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
  		 <property name="connectionFactory" ref="qpidConnectionFactory"/>
  		 <property name="defaultDestination" ref="qpidQueue"/>
 	</bean>


 - 發送消息的代碼
static class sendQpid implements Runnable{
		String strMessage = null;
		boolean isSuccess = true;
		
		@Override
		public void run() {
			while(true){
				try {
					if(isSuccess){
						// 若是上一條消息發送成功,則取出下一條消息
						strMessage = qpidMessageQueue.take();
					}
					// 將消息轉換成byte數組,便於發送
					final byte[] output = ZipUtils.gzipToByteArray(strMessage);
					logger.info("-------------->sent message to QPID,length:"+output.length);
					qpidJmsTemplate.send(new MessageCreator() {
						public Message createMessage(Session session) throws JMSException {
							MapMessage message = session.createMapMessage();
							message.setBytes("body", output);
							return message;
						}
					});
					// 標記這條消息發送成功
					isSuccess = true;
					// 將消息記錄到特定文件中,實現對發送消息的監控
//					monitorLogger.info(strMessage);
				}catch(JmsException e){
					isSuccess = false;
					logger.error(e.getLocalizedMessage());
				} catch (InterruptedException e) {
					isSuccess = false;
					logger.error(e.getLocalizedMessage());
				} catch (IOException e) {
					isSuccess = false;
					logger.error(e.getLocalizedMessage());
				}
			}
		}
	}
相關文章
相關標籤/搜索