1. 创建项目,添加ActiveMQ依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
2. 在application.properties中进行连接配置
spring.activemq.broker-url=tcp://localhost:61616 #端口
spring.activemq.packages.trust-all=true #信任所有的包
spring.activemq.user=admin #用户名
spring.activemq.password=admin #密码
编码
提供一个消息队列Bean,该Bean的实例就由ActiveMQ提供:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
Queue queue(){
return new ActiveMQQueue("amq");
}
}
创建一个JMS组件来完成消息的发送和接收:
@Component
public class JmsComponent {
@Autowired
JmsMessagingTemplate messagingTemplate;
@Autowired
Queue queue;
public void send(Message msg){
messagingTemplate.convertAndSend(this.queue, msg);
}
@JmsListener(destination = "amq")
public void receive(Message msg){
System.out.println("receive:" + msg);
}
}
4. 测试
@Autowired
JmsComponent jmsComponent;
@Test
public void test(){
Message msg = new Message();
msg.setContent("hello jms!");
msg.setDate(new Date());
jmsComponent.send(msg);
}
控制台打印:
receive:com.example.demo.pojo.Message@78a8611e