【springboot整合ActiveMQ】

加入依赖,配置ActiveMQ启动器

<!-- 配置ActiveMQ启动器 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-activemq</artifactId>

</dependency>

创建队列

引导类
@SpringBootApplication
@EnableCaching
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    } 

    @Bean
    public Queue queue() {
    
        return new ActiveMQQueue("cnn.queue");
    }
}
发送消息:
Controller类
@RestController
@RequestMapping("queue")
public class QueueController {
    //注入发送消息的对象
    @Autowired
    private JmsTemplate jmsTemplate; 
    //注入消息队列
    @Autowired
    private Destination destination;
    //编写发送消息的方法
    @RequestMapping("send/{message}")
    public String send(@PathVariable String message) {

    this.jmsTemplate.convertAndSend(destination, message);

    return "消息发送成功!消息内容:" + message;

    }
}
接受消息:
@Component
public class Consumer {

    // 接受消息方法
    @JmsListener(destination = "cnn.queue")
    public void readMessage(String text) {

        System.out.println("接受到的消息是:" + text);

    }

}

因为Spring Boot 内置了ActiveMQ 的服务,所以我们不用单独启动也可以实现消息的发送和接收

使用外部的ActiveMQ

#ActiveMQ

spring.activemq.broker-url=tcp://192.168.37.161:61616 

这样就加入了ActiveMQ服务的地址


测试:
<!-- 配置测试启动器 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)    //指定引导类的class
public class MessageTest {


    @Autowired
    private Destination destination;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Test
    public void test() {

        System.out.println("我发消息了!");

        this.jmsTemplate.convertAndSend(destination, "Hello ActiveMQ!");

    }

}



全部评论

相关推荐

09-22 22:22
中山大学 Java
双尔:赌对了,不用经历秋招的炼狱真的太好了,羡慕了
点赞 评论 收藏
分享
野猪不是猪🐗:还是太卑微了,什么叫放弃本次面试应该说经过评估,贵公司与自己不匹配,决定不再推进后续流程
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务