引入依赖
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
</dependency>
YML文件配置
rocketmq:
name-server: ${ROCKETMQ_SERVER:你的rockectmq地址}
producer:
group: xxxx
服务端发送消息
搞个工具类,方便公共调用
public class MsgProviderHelper {
private static final RocketMQTemplate rocketMQTemplate = SpringContextHelper.getInstance(RocketMQTemplate.class);
public static void sendDefMsg(String target, Object data) {
SendResult send = rocketMQTemplate.syncSend(target, MessageBuilder.withPayload(toJson(data)).build());
if (!send.getSendStatus().equals(SendStatus.SEND_OK)) {
throw new RuntimeException("发送失败");
}
}
public static void sendDefMsg(String target, String tag, Object data) {
if (StrUtil.isNotEmpty(tag)) {
target += ":" + tag;
}
sendDefMsg(target, data);
}
private static String toJson(Object data) {
return JSONUtil.toJsonStr(data);
}
}
然后直接通过该工具类把你的topic和数据传过去调用就可以了
通过上下文拿bean 工具类
@Component
public class SpringContextHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(@NonNull ApplicationContext context) {
applicationContext = context;
}
public static <T> T getInstance(String beanName, Class<T> beanType) {
return applicationContext.getBean(beanName, beanType);
}
public static <T> T getInstance(Class<T> bean) {
return applicationContext.getBean(bean);
}
}
消费端接收消息
@Component
@RocketMQMessageListener(topic = "你的topic", consumerGroup = "你的消费组")
@RequiredArgsConstructor
public class HardwareLayoutListener implements RocketMQListener<String> {
@Override
public void onMessage(String s) {
//里头写你具体业务逻辑
}
}