spring boot整合activemq消息中间件
4.0.0 zxf-active zxf-active 0.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-parent 1.5.2.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-activemq org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
package com.newtouch.active.service;import javax.jms.Destination;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jms.core.JmsTemplate;import org.springframework.stereotype.Service;@Service("JmsProducer")public class JmsProducer { @Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装 private JmsTemplate jmsTemplate; // 发送消息,destination是发送到的队列,message是待发送的消息 public void sendMessage(Destination destination, final String message){ jmsTemplate.convertAndSend(destination, message); } }
package com.newtouch.active.service;import org.springframework.jms.annotation.JmsListener;import org.springframework.stereotype.Component;@Componentpublic class JmsConsumer { // 使用JmsListener配置消费者监听的队列,其中text是接收到的消息 @JmsListener(destination = "mytest.queue") public void receiveQueue(String text) { System.out.println("Consumer收到的报文为:"+text); } }
package com.newtouch.active.controller;import java.util.HashMap;import java.util.Map;import javax.jms.Destination;import org.apache.activemq.command.ActiveMQQueue;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.newtouch.active.service.JmsProducer;@RestController@RequestMapping("/active")public class ActiveController { @Autowired private JmsProducer jmsProducer; @RequestMapping("/test") private Maptest(){ Map resultMap = new HashMap (); Destination destination = new ActiveMQQueue("mytest.queue"); for(int i=0; i<100; i++){ jmsProducer.sendMessage(destination, "myname is chhliu!!!"); } resultMap.put("code", "1"); return resultMap; } }
spring.activemq.broker-url=tcp://localhost:61616spring.activemq.user=adminspring.activemq.password=adminspring.activemq.in-memory=truespring.activemq.pool.enabled=falsespring.application.name=SERVICE-ACTIVEserver.port=8090server.contextPath=/
成功打印消息