package com.doumee.config.rocketmq5; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.rocketmq.client.apis.ClientConfiguration; import org.apache.rocketmq.client.apis.ClientException; import org.apache.rocketmq.client.apis.ClientServiceProvider; import org.apache.rocketmq.client.apis.SessionCredentialsProvider; import org.apache.rocketmq.client.apis.StaticSessionCredentialsProvider; import org.apache.rocketmq.client.apis.message.Message; import org.apache.rocketmq.client.apis.producer.Producer; import org.apache.rocketmq.client.apis.producer.SendReceipt; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Service @Slf4j public class NormalMsgProducer { @Autowired public MqConfig mqConfig; public boolean sendMsg(String tag,String msg) { try { final ClientServiceProvider provider = ClientServiceProvider.loadService(); StaticSessionCredentialsProvider staticSessionCredentialsProvider = new StaticSessionCredentialsProvider(mqConfig.getUsername(), mqConfig.getPassword()); String endpoints = mqConfig.getNameSrvAddr(); ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder() .setEndpoints(endpoints) .setCredentialProvider(staticSessionCredentialsProvider) .build(); String topic = mqConfig.getTopic(); // In most case, you don't need to create too many producers, singleton pattern is recommended. final Producer producer = provider.newProducerBuilder() .setClientConfiguration(clientConfiguration) // Set the topic name(s), which is optional but recommended. It makes producer could prefetch the topic // route before message publishing. .setTopics(topic) // May throw {@link ClientException} if the producer is not initialized. .build(); // Define your message body. byte[] body = msg.getBytes(StandardCharsets.UTF_8); final Message message = provider.newMessageBuilder() // Set topic for the current message. .setTopic(topic) // Message secondary classifier of message besides topic. .setTag(tag) // Key(s) of the message, another way to mark message besides message id. // .setKeys(null) .setBody(body) .build(); final SendReceipt sendReceipt = producer.send(message); log.info("Send message successfully, messageId={}", sendReceipt.getMessageId()); // Close the producer when you don't need it anymore. producer.close(); return true; }catch (Exception e){ e.printStackTrace(); } return false; } }