Spring集成ActiveMQ
来源:互联网 发布:知乎注册首页 编辑:程序博客网 时间:2024/06/03 22:48
1、配置bean
<bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>${MQ.ADDRESS}</value>
</property>
<property name="useAsyncSend">
<value>true</value>
</property>
</bean>
</property>
</bean>
<!-- 配置JMS模版 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<!-- 消息发布bean -->
<bean id="publishServiceImpl" class="com.*.PublishServiceImpl" scope="singleton">
<!-- 消息监听bean-->
<bean id="messageListenerAdviceImpl" class="com.*.MessageListenerAdviceImpl"
init-method="init" scope="singleton">
2、发消息实现类应用:
public class PublishServiceImpl implements PublishService
{
private static final String JMS_MESSAGE = "jms/message";
private static final String UTF_8 = "UTF-8";
private static final String JMS_ENCODE = "Encode/Decode";
private static final String JMS_JMSXMIMETYPE = "JMSXMimeType";
private static final String JMS_GROUPID = "groupID";
private static final String JMS_DESTINATION = "destination";
@Resource
private JmsTemplate jmsTemplate;
private static final String SUBPUB_TRUE = "true";
/**
* @Title: send
* @Description: 发送JMS消息
*
* @param mqBean
* 业务[groupID 业务类型
*/
@Override
public void send(MQBean mqBean) throws FrameException
{
MessageConfigBean messageConfigBean = (MessageConfigBean) SpringContextUtil
.getObject(Constants.MESSAGE_CONFIG_BEAN);
if(Constants.SERVICE_OPERATIONTYPE_ORDER.equals(mqBean.getGroupId()))
{
ActiveMQTextMessage textMsg = new ActiveMQTextMessage();
textMsg.setGroupID(mqBean.getGroupId());
if(null != textMsg.getMessageId())
{
mqBean.setMessageId(textMsg.getMessageId().toString());
}
try
{
// 请求JSON
String payload = JsonUtils.getJosnFromObject(mqBean);
textMsg.setText(payload);
textMsg.setProperty(JMS_ENCODE, UTF_8);
textMsg.setProperty(JMS_JMSXMIMETYPE, JMS_MESSAGE);
}
catch (MessageNotWriteableException e)
{
throw new FrameException(MessageCode.CREATE_JMS_MESSAGE_EXCEPTION, e);
}
catch (IOException e)
{
throw new FrameException(MessageCode.CREATE_JMS_MESSAGE_EXCEPTION, e);
}
this.send(textMsg, messageConfigBean);
}
else if(Constants.SERVICE_OPERATIONTYPE_WAYBILL.equals(mqBean.getGroupId()))
{
// 请求JSON
String payload = JsonUtils.getJosnFromObject(mqBean);
Map<String, Object> headers = new HashMap<String, Object>();
headers.put(JMS_ENCODE, UTF_8);
headers.put(JMS_JMSXMIMETYPE, JMS_MESSAGE);
headers.put(JMS_GROUPID, mqBean.getGroupId());
headers.put(JMS_DESTINATION, messageConfigBean.getSendWBSCQueueID());
GenericMessage<String> message = new GenericMessage<String>(
payload, headers);
this.send(message, messageConfigBean);
}
}
/**
* @Title: send
* @Description: 通过管道过滤器发送消息 (用于运单中心)
*
* @param message 待发送消息
* @param messageConfigBean 消息队列配置
*/
public void send(GenericMessage<?> message, MessageConfigBean messageConfigBean)
throws FrameException
{
try
{
String pubSubDomain = messageConfigBean.getSendWBSCPubSubDomain();
boolean isSubDomain = false;
if (StringUtils.isNotEmpty(pubSubDomain) && SUBPUB_TRUE.equals(pubSubDomain.trim()))
{
isSubDomain = true;
}
// 设置消息订阅方式【是否发布订阅方式 true:是】
jmsTemplate.setPubSubDomain(isSubDomain);
JmsSendingMessageHandler jmsSendingMessageHandler = new JmsSendingMessageHandler(
jmsTemplate);
String queueID = messageConfigBean.getSendWBSCQueueID();
ActiveMQQueue activeMQQueue = new ActiveMQQueue(queueID);
jmsSendingMessageHandler.setDestination(activeMQQueue);
DirectChannel queueChannel = new DirectChannel();
queueChannel.subscribe(jmsSendingMessageHandler);
queueChannel.send(message);
}
catch (Exception e)
{
}
}
/**
* @Title: send
* @Description: 通过管道过滤器发送消息 (用于订单中心)
*
* @param message 待发送消息
* @param messageConfigBean 消息队列配置
*/
public void send(Message message, MessageConfigBean messageConfigBean) throws FrameException
{
try
{
boolean isSubDomain = false;
String pubSubDomain = messageConfigBean.getSendEOSCPubSubDomain();
if (StringUtils.isNotEmpty(pubSubDomain) && SUBPUB_TRUE.equals(pubSubDomain.trim()))
{
isSubDomain = true;
}
// 设置消息订阅方式【是否发布订阅方式 true:是】
jmsTemplate.setPubSubDomain(isSubDomain);
String queueID = messageConfigBean.getSendEOSCQueueID();
ActiveMQQueue activeMQQueue = new ActiveMQQueue(queueID);
message.setDestination(activeMQQueue);
jmsTemplate.convertAndSend(activeMQQueue, message);
}
catch (Exception e)
{
}
}
}
2、消息处理
/**
* 消息预处理 用于在接收到消息后,需要在消息处理前对消息进行统一预处理的场景 。
*/
@Service
public class RetrievePayloadImpl implements RetrievePayload
{
@Override
public GenericMessage<?> getPayload(GenericMessage<?> message)
{
return message;
}
@Override
public Message getPayload(Message message)
{
return message;
}
}
3、监听收消息
/**
* 消息监听器
*
*/
@Service
public class MessageListenerImpl implements MessageListener
{
private Logger logger = LoggerFactory.getLogger(MessageListenerImpl.class);
/** 消息組ID Key名 */
private static final String JMS_GROUP_ID = "groupID";
private static final String JMSX_GROUP_ID = "JMSXGroupID";
private static final String JMS_MESSAGE_IS_NULL = "JMS MESSAGE IS NULL";
private static final String UNSUPPORTTED_ACCESSTYPE = "unsupportted accesstype:";
@Resource
private IWayBillServiceMessage wayBillServiceMessage;
@Resource
private IOrderService orderService;
@Resource
private PublishService publishServiceImpl;
/**
* @Title: processMessage
* @Description: 对接收到的消息,依据消息关键字进行相应的处理
*/
public void processMessage(GenericMessage<?> message)
{
}
/**
* @Title: processMessage
* @Description: 对接收到的消息,依据消息关键字进行相应的处理
*/
public void processMessage(Message message)
{
}
/**
* @Title: decodeMessage
* @Description: 消息解析
*
* @param message
* Spring集成消息
*/
private void decodeMessage(GenericMessage<?> message, String groupID) throws FrameException
{
String text = (String) message.getPayload();
if (StringUtils.isEmpty(text))
{
throw new FrameException(MessageCode.GET_JMS_MESSAGE_EXCEPTION, JMS_MESSAGE_IS_NULL);
}
}
/**
* @Title: decodeMessage
* @Description: 消息解析
*
* @param message
* activemq消息
*/
private void decodeMessage(Message message) throws FrameException
{
ActiveMQTextMessage textMessage = null;
if (message instanceof ActiveMQTextMessage)
{
textMessage = (ActiveMQTextMessage) message;
}
String text = null;
try
{
text = textMessage.getText();
}
catch (JMSException e1)
{
throw new FrameException(MessageCode.GET_JMS_MESSAGE_EXCEPTION, e1);
}
if (StringUtils.isEmpty(text))
{
throw new FrameException(MessageCode.GET_JMS_MESSAGE_EXCEPTION, JMS_MESSAGE_IS_NULL);
}
}
/**
* @Title: decodeMessage
* @Description: 消息解析
*
*/
private void decodeMessage(String message) throws FrameException
{
}
}
4、消息监听器
/**
* 消息监听器
*
* */
public class MessageListenerAdviceImpl implements MessageListenerAdvice
{
private static final String MESSAGE_CONFIG_BEAN = "messageConfigBean";
private static final String TRUE = "true";
/** 连接消息对列的key */
private static final String CONNECTION_FACTORY = "connectionFactory";
/** RetrievePayload类的业务处理方法 */
private static final String GET_PAYLOAD = "getPayload";
/** MessageListener类的业务处理方法 */
private static final String PROCESS_MESSAGE = "processMessage";
/** RetrievePayload类获取失败时的日志信息 */
private static final String RETRIEVE_PAYLOAD_FAILURE = "[RetrievePayload] Getting the target object is failure.";
/** MessageListener类获取失败时的日志信息 */
private static final String MESSAGE_LISTENER_FAILURE = "[MessageListener] Getting the target object is failure.";
@Resource
private RetrievePayload retrievePayloadImpl;
@Resource
private MessageListener messageListenerImpl;
/**
* @Title: init
* @Description: 依据管道过滤器的方式(通过spring integration)初始化。
*/
@Override
public void init() throws FrameException
{
MessageConfigBean messageConfigBean = (MessageConfigBean) SpringContextUtil
.getObject(MESSAGE_CONFIG_BEAN);
String tenantID = messageConfigBean.getTenantId();
String []tenantIDs = tenantID.split("\\|");
createMessageListener(messageConfigBean, tenantIDs);
}
/**
* @Title: createMessageListener
* @Description: 创建消息监听类
*
*/
private void createMessageListener(MessageConfigBean messageConfigBean, String [] tenantIDs)
throws FrameException
{
for (String tenantID : tenantIDs)
{
// 定义消息监听容器
DefaultMessageListenerContainer defaultMessageListenerContainer = new DefaultMessageListenerContainer();
// 获取消息队列服务
ConnectionFactory connectionFactory = (ConnectionFactory) SpringContextUtil
.getObject(CONNECTION_FACTORY);
defaultMessageListenerContainer.setConnectionFactory(connectionFactory);
StringBuilder sbu = new StringBuilder();
sbu.append(messageConfigBean.getReceiveQueueIDPrefix());
sbu.append(".");
sbu.append(tenantID);
// 定义监听目标
ActiveMQQueue activeMQQueue = new ActiveMQQueue(sbu.toString());
defaultMessageListenerContainer.setDestination(activeMQQueue);
String pubSubDomain = messageConfigBean.getReceivePubSubDomain();
boolean isSubDomain = false;
if (StringUtils.isNotEmpty(pubSubDomain) && TRUE.equals(pubSubDomain.trim()))
{
isSubDomain = true;
}
// 设置消息订阅方式【是否发布订阅方式 true:是】
defaultMessageListenerContainer.setPubSubDomain(isSubDomain);
// 设置消息确认模式
if (StringUtils.isNotEmpty(messageConfigBean.getAcknowledge()))
{
defaultMessageListenerContainer.setSessionAcknowledgeMode(Integer
.parseInt(messageConfigBean.getAcknowledge()));
}
defaultMessageListenerContainer.initialize();
// 定义管道过滤器,用于路由队列中的消息
DirectChannel getPayloadChannel = new DirectChannel();
ChannelPublishingJmsMessageListener channelPublishingJmsMessageListener = new ChannelPublishingJmsMessageListener();
channelPublishingJmsMessageListener.setRequestChannel(getPayloadChannel);
JmsMessageDrivenEndpoint jmsMessageDrivenEndpoint = new JmsMessageDrivenEndpoint(
defaultMessageListenerContainer, channelPublishingJmsMessageListener);
// 消息拦截类,用于扩展。(获取到原有的对象)
RetrievePayload retrievePayload = null;
try
{
retrievePayload = (RetrievePayload) (AopTargetUtils.getTarget(retrievePayloadImpl));
}
catch (Exception e)
{
throw new FrameException(MessageCode.GET_VALUE_EXCEPTION, RETRIEVE_PAYLOAD_FAILURE,
e);
}
// 关联消息处理的业务组件及其方法
ServiceActivatingHandler messageHandler = new ServiceActivatingHandler(retrievePayload,
GET_PAYLOAD);
// 定义管道过滤器路由消息的业务处理类【消费者】
getPayloadChannel.subscribe(messageHandler);
// 定义管道过滤器,用于路由业务处理过滤器过滤过的消息
DirectChannel listenerChannel = new DirectChannel();
messageHandler.setOutputChannel(listenerChannel);
// 消息最终处理的业务类,(获取到原有的对象)
MessageListener messageListener = null;
try
{
messageListener = (MessageListener) (AopTargetUtils.getTarget(messageListenerImpl));
}
catch (Exception e)
{
throw new FrameException(MessageCode.GET_VALUE_EXCEPTION, MESSAGE_LISTENER_FAILURE,
e);
}
// 关联消息处理的业务组件及其方法
ServiceActivatingHandler messageHandlerEnd = new ServiceActivatingHandler(
messageListener, PROCESS_MESSAGE);
// 定义管道过滤器路由消息的业务处理类【消费者】
listenerChannel.subscribe(messageHandlerEnd);
defaultMessageListenerContainer.start();
jmsMessageDrivenEndpoint.start();
}
}
}
- ActiveMQ(二) ActiveMQ + spring 集成
- Spring集成ActiveMQ配置
- Spring集成ActiveMQ配置
- spring activemq集成封装
- ActiveMQ和spring集成
- Spring 和activemq集成
- Spring集成ActiveMQ
- Spring集成ActiveMQ
- Spring集成ActiveMQ
- Spring集成ActiveMQ
- Spring集成ActiveMQ
- spring+activemq+maven集成
- ActiveMq集成spring
- Spring集成ActiveMQ
- spring-boot集成ActiveMQ
- spring-boot 集成 activemq
- spring-boot 集成 activemq
- spring 集成activemq
- IO操作
- 验证码倒计时函数
- php中文正则
- kafka学习(二)--windows下安装配置
- vs2012+wdk8.0编译出错
- Spring集成ActiveMQ
- 【HDU1166】【线段树】【单点更新】【左闭右开】
- HDU - 4687(带花树求最大匹配的变形)
- 白话经典算法系列之一 冒泡排序的三种实现
- Ubuntu中Atom编辑器显示中文乱码的处理方法
- 安装hive-1.2.1详细步骤
- hdu 5396 Expression(区间dp+组合数)
- JS高级程序设计读书笔记(第一章到第五章)
- B. Order Book------(Codeforces Round #317 [AimFund Thanks-Round] (Div. 2))