ActiveMQ在使用的时候跟RabbitMQ有所不同,RabbitMq在使用的时候是通过Queue进行设置消息,但是ActiveMQ在设置消息的时候,是通过实现MessageCreator类,重写里面的createMessage方法,将要发送的数据放到session中。
配置
package com.activemq.activemq.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsTemplate;
@Configuration
public class ActiveMQConfig implements CommandLineRunner {
@Autowired
private JmsTemplate jmsTemplate;
@Override
public void run(String... args) throws Exception {
jmsTemplate.send("my-activeMq", new Msg());
}
}
MessageCreator的实现类
package com.activemq.activemq.Config;
import org.springframework.jms.core.MessageCreator;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
public class Msg implements MessageCreator {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("activeMq发送消息");
}
}
监听服务发布方:
package com.activemq.activemq.Wisely;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class ActiveMQLis {
@JmsListener(destination = "my-activeMq")
public void getActiveMQMessage(String message) {
System.out.println("接收的消息:" + message);
}
}
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>