SpringBoot项目嵌入RocketMQ

在Spring Boot中嵌入RocketMQ可以通过添加相应的依赖来完成。首先需要在pom.xml文件中引入spring-boot-starter-amqp依赖:


    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-data-jpa
    
    
        org.apache.rocketmq
        rocketmq-spring-boot-starter
        2.1.0
    
    
        org.projectlombok
        lombok
    

然后,在application.properties或者application.yml配置文件中设置RocketMQ连接信息:

# RocketMQ服务器地址

rocketmq.name-server=127.0.0.1:9876

# 生产者分组

rocketmq.producer.group=my-group

最后,创建消息发送者(Producer)和消息接收者(Consumer)类,并使用@Autowired注解将其自动装载到Spring容器中。示例如下:

创建消息发送者类:

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProducerController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;    

    @GetMapping("/send")
    public String send(String message) {
        rocketMQTemplate.convertAndSend("test-topic", message);
        return "Message: '" + message + "' sent.";
    }

}

创建消息接收者类:

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

@Service
@RocketMQMessageListener(topic = "test-topic", consumerGroup = "my-consumer_test-topic")
public class ConsumerService implements RocketMQListener {

    @Override
    public void onMessage(String message) {
        System.out.printf("------- StringConsumer received: %s \n", message);
    }
}

当调用/send接口时,会向"myQueue"队列发送消息;

MessageReceiver则会监听该队列,并处理接收到的消息。

查看控制台的输出来验证消息消费者是否可以正常接收消息

你可能感兴趣的:(java,linux,spring,boot,java-rocketmq,rocketmq)