maven项目ActiveMQ集成

1.linux下activemq安装与配置

1.1、下载:apache-activemq-5.14.0-bin.tar.gz

http://activemq.apache.org/activemq-5140-release.html

1.2、安装activemq

1.2.1、gz文件拷贝到/usr/local/src目录

1.2.2、解压启动

tar -zxvf apache-activemq-5.14.0-bin.tar.gz

cd apache-activemq-5.14.0

cd bin

./activemq start

 netstat -anp|grep 61616

1.3、开启防火墙端口

1.3.1、如果使用了云服务器需要先开启8161(web管理页面端口)、61616(activemq服务监控端口) 两个端口

1.3.2、打开linux防火墙端口

/sbin/iptables -I INPUT -p tcp --dport 8161 -j ACCEPT&&/etc/init.d/iptables save&&service iptables restart&&/etc/init.d/iptables status

/sbin/iptables -I INPUT -p tcp --dport 61616 -j ACCEPT&&/etc/init.d/iptables save&&service iptables restart&&/etc/init.d/iptables status

1.4、打开web管理页面

http://IP:8161/admin

默认用户名密码 admin/admin 

1.5、安全配置

http://activemq.apache.org/security.html

1.5.1、activemq.xml新增账号密码(broker标签下添加)


<simpleAuthenticationPlugin>
    <users>
        <authenticationUser username="system" password="manager"
            groups="users,admins"/>
        
    </users>
</simpleAuthenticationPlugin>

1.5.2、程序代码中添加账号密码

 

2. ActiveMQ集成

2.1 pom.xml中引入必要包

                <!-- mq消息集成 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jms</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-pool</artifactId>
		</dependency>

2.2 xml文件spring-activeMQ-config.xml中必要配置添加

<!-- spring提供的jms工具类,进行消息的发送、接收 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
        <property name="connectionFactory" ref="connectionFactory"></property>
        <property name="receiveTimeout" value="10000"/>
        <property name="sessionTransacted" value="true"/>
    </bean>

    <!-- 真正可以产生Connection的ConnectionFactory,由对应的JMS厂商提供,activeMQ ${schema}://${host}:${port}-->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <!-- property name="brokerURL" value="${schema}://${host}:${port}"></property -->
        <property name="brokerURL" value="failover:(${schema})&amp;maxReconnectDelay=1000"></property>
        <property name="userName" value="${userName}"></property>
        <property name="password" value="${password}"></property>
    </bean>
	
	<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
	    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>  
	</bean> 

2.3 消息接收配置spring-activeMQ-config.xml中添加

<!-- resultStatus队列目的地-->
	<bean id="resultStatusQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="${resultStatus.res}"/>
    </bean>
	<!-- resultStatus消息接收监听器用于异步接收消息-->
	<bean id="resultStatusContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="destination" ref="resultStatusQueue"/>
        <property name="messageListener" ref="resultStatusListener"/>
    </bean>
    <!-- resultStatus消息监听实现方法一 -->
    <bean id="resultStatusListener" class="com.xxxxxx.hyom.outeradmin.listener.ResultStatusInfoListener"></bean>

2.4 消息接收监听类实现 :

com.xxxxxx.hyom.outeradmin.listener.ResultStatusInfoListener

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class ResultStatusInfoListener implements MessageListener {
	
	private final Logger log = LoggerFactory.getLogger(ResultStatusInfoListener.class);
	
	@Override
	public void onMessage(Message message) {
		// TODO Auto-generated method stub
		log.info("ResultStatusInfoListener 接收消息 start......");
		TextMessage tm = (TextMessage) message;
		String text;
		try {
			text = tm.getText();
			log.info("ResultStatusInfoListener text:{}", text);
		} catch (JMSException e) {
			e.printStackTrace();
		}
		log.info("ResultStatusInfoListener 接收消息 end......");
	}
}

 

2.5 消息发送接口实现

import javax.annotation.Resource;
import javax.jms.JMSException;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import com.xxxxxx.eosc.order.entity.SendMqBean;
import com.xxxxxx.eosc.order.service.ISendMqMessageService;
import com.xxxxxx.framework.core.Result;
import net.sf.json.JSONObject;

/**
 * 消息具体发送接口
 */
@Service
public class SendMqMessageServiceImpl implements ISendMqMessageService {
	private static final Logger LOGGER = LoggerFactory.getLogger(SendMqMessageServiceImpl.class);

	@Resource
	private JmsTemplate jmsTemplate;

	/**
	 * 20160608 James 修改: 
	 * <p>1. 发消息前创建session时,设置acknowledge模式为CLIENT_ACKNOWLEDGE,
	 * 使得consumer消费完消息后,可以通过调用acknowledge()方法向producer发送确认消息,producer
	 * 收到确认消息后,会将消息从消息队列移除;如果producer没有收到确认消息,producer会继续发送,
	 * 发送达到6次后,还未收到consumer的确认消息的话,producer就会将消息从原队列中移到activeMQ的
	 * 自带队列中,并不再继续发送。
	 * 
	 * <p>2. 消息发送失败后抛出RuntimeException,保证发消息和订单中心业务逻辑在一个事务中。
	 * 
	 * destination 消息队列名
	 * sendMqBean  消息内容实体
	 */
	@Override
	public Result sendMessage(String destination, SendMqBean sendMqBean) {
		Result result = new Result();
		LOGGER.info("[ISendMqMessageService] sendMessage enter destinationName "+ destination);
		
		ActiveMQTextMessage textMsg = new ActiveMQTextMessage();
		try {
			if (destination == null || "".equals(destination)) {
				LOGGER.info("[ISendMqMessageService] sendMessage destinationName is empty.");
				result.setSuccess(false);
				result.setMsg("消息队列为空");
				result.setMsgCode("-1");
				return result;
			}

			if (sendMqBean == null) {
				LOGGER.info("[ISendMqMessageService] sendMessage Sending jms orderInfo is not allow null.");
				result.setSuccess(false);
				result.setMsg("消息内容为空");
				result.setMsgCode("-2");
				return result;
			}
			JSONObject json = JSONObject.fromObject(sendMqBean);
			LOGGER.info("[ISendMqMessageService] sendMessage content:"+ json.toString());

			textMsg.setGroupID("ORDER"); // 组别标识
			textMsg.setGroupSequence(0);//组别排序
			textMsg.setText(json.toString()); // 业务属性
			jmsTemplate.convertAndSend(destination, textMsg);
			LOGGER.info("[ISendMqMessageService] sendMessage sending...");
			
			result.setSuccess(true);
			result.setMsg("发送成功");
			result.setMsgCode("0");
		} catch (JMSException e) {
			LOGGER.error("[ISendMqMessageService] sendMessage send message error "
					+ e.getLocalizedMessage());
			// 抛出运行时异常,让事务回滚
			throw new RuntimeException(e);
		}
		LOGGER.info("[ISendMqMessageService] sendMessage exit destinationName "+ textMsg);
		return result;
	}
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值