package com.anve.coupon.basic.rocketmq; import com.anve.coupon.basic.logic.ConfigLogic; import com.anve.coupon.domain.constant.Constans; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.common.message.Message; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * linggan on 2017/12/20 */ @Service public class SyncProducer { private static final Logger logger = LogManager.getLogger(SyncProducer.class); private DefaultMQProducer producer; @Autowired ConfigLogic configLogic; /** * 初始化mq */ private void init() { try { //组名称 String groupName = Constans.COUPON_UPDATE_ORDER_GROUPNAME; //mq地址 String ipAddress = configLogic.getKey(ConfigLogic.ROCKETMQ_IP); //实例化一个生产者组名称。 producer = new DefaultMQProducer(groupName); producer.setNamesrvAddr(ipAddress); producer.start(); logger.debug("Method[initMq]初始化mq成功:生产者组名称:{},mq地址:{}", groupName, ipAddress); } catch (MQClientException e) { logger.error("Method[initMq]初始化mq异常:{}", e.getMessage(), e); } } /** * 批量放消息 * * @param data * @return */ public boolean push(List<String> data) { if (CollectionUtils.isEmpty(data)) { return false; } for (String message : data) { push(Constans.COUPON_UPDATE_ORDER_TOPIC, Constans.COUPON_UPDATE_ORDER_TAG, message); } return true; } /** * 放消息 * * @param topic * @param tag * @param body * @return */ public boolean push(String topic, String tag, String body) { if (StringUtils.isEmpty(topic) || StringUtils.isEmpty(tag) || StringUtils.isEmpty(body)) { logger.debug("Method[push]topic,tag,body参数有空,topic:{},tag:{},body:{}", topic, tag, body); return false; } try { Message msg = new Message(topic, tag, (body).getBytes()); SendResult sendResult = producer.send(msg); logger.debug("Method[push]Mq放消息结果;{}", sendResult); } catch (Exception e) { logger.debug("Method[push]放消息异常,topic:{},tag:{},body:{},错误信息:{}", topic, tag, body, e.getMessage(), e); } return true; } /** * 一旦生产者实例不再使用,就关闭它。 */ public void shutdown() { producer.shutdown(); logger.debug("Method[shutdown]Mq生产者实例销毁"); }
<!--recketmq初始化--> <bean id="syncProducer" class="com.anve.coupon.basic.rocketmq.SyncProducer" scope="singleton" init-method="init" destroy-method="shutdown"> </bean>}
本列子参照官网写法,官网有批量放消息的方法,使用好像没用,欢迎交流