1
This commit is contained in:
@@ -1,8 +1,16 @@
|
||||
package cn.van.business.mq;
|
||||
|
||||
import cn.van.business.util.WXUtil;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import lombok.SneakyThrows;
|
||||
import org.apache.rocketmq.client.exception.MQClientException;
|
||||
import org.apache.rocketmq.client.producer.DefaultMQProducer;
|
||||
import org.apache.rocketmq.client.producer.MQProducer;
|
||||
import org.apache.rocketmq.spring.core.RocketMQTemplate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.apache.rocketmq.common.message.Message;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
@@ -14,13 +22,38 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
public class MessageProducerService {
|
||||
|
||||
@Autowired
|
||||
private RocketMQTemplate rocketMQTemplate;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageProducerService.class);
|
||||
|
||||
private static final String topic = "wx-message";
|
||||
|
||||
private static volatile DefaultMQProducer shareProducer;
|
||||
|
||||
public MQProducer getProducer() throws MQClientException {
|
||||
if (shareProducer == null) {
|
||||
synchronized (MQProducer.class) {
|
||||
if (shareProducer == null) {
|
||||
shareProducer = createProducer();
|
||||
}
|
||||
}
|
||||
}
|
||||
return shareProducer;
|
||||
}
|
||||
|
||||
public DefaultMQProducer createProducer() throws MQClientException {
|
||||
|
||||
DefaultMQProducer producer = new DefaultMQProducer("wx_producer");
|
||||
producer.setNamesrvAddr("192.168.8.88:9876");
|
||||
producer.start();
|
||||
|
||||
logger.info("shareProducer[{}|{}]", "wx_producer", producer.getNamesrvAddr());
|
||||
|
||||
return producer;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public void sendMessage(JSONObject jsonObject) {
|
||||
this.rocketMQTemplate.convertAndSend(topic, jsonObject.toJSONString());
|
||||
Message message = new Message(topic, jsonObject.toJSONString().getBytes());
|
||||
getProducer().send(message);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user