window环境本地搭建环境
ActiveMQ官网下载地址:http://activemq.apache.org/download.html
安装完成后启动
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
启动类:
@SpringBootApplication
@EnableJms
public class testApplication {
Logger logger= LogManager.getLogger(getClass());
@Bean
public ActiveMQQueue queue() {
return new ActiveMQQueue("promoteAct");
}
//没有这段注入可能会出错
@Bean
public ConnectionFactory connectionFactory(){
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL("tcp://localhost:61616");
connectionFactory.setUserName("admin");
connectionFactory.setPassword("admin");
logger.info("连接mq完成");
return connectionFactory;
}
@Bean
public JmsTemplate genJmsTemplate(){
return new JmsTemplate(connectionFactory());
}
@Bean
public JmsMessagingTemplate jmsMessageTemplate(){
return new JmsMessagingTemplate(connectionFactory());
}
public static void main(String[] args) {
SpringApplication.run(LinuxtestApplication.class, args);
}
/**
* 生产者
*/
@RestController
public class Productor {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private ActiveMQQueue queue;
@RequestMapping("/sendMsg")
public void send(String msg) {
jmsMessagingTemplate.convertAndSend(this.queue, msg);
}
}
/**
* 消费者
*/
@Component
public class Customer {
Logger logger = LogManager.getLogger(getClass());
@JmsListener(destination = "promoteAct")
public void receiveQueue(String message) {
logger.info("消息已经消费 message:" + message);
}
}