Springboot 2.0 整合 ActiveMQ

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AnselLyy/article/details/81044320

CentOS7 服务器安装 ActiveMQ 5.15.4

wget http://www.apache.org/dyn/closer.cgi?filename=/activemq/5.15.4/apache-activemq-5.15.4-bin.tar.gz&action=download
tar -zxvf apache-activemq-5.15.4-bin.tar.gz
cd apache-activemq-5.15.4/bin/linux-x86-64
./activemq start

在 localhost:8161 可以进入 ActiveMQ 的控制面板

Springboot 2.0 整合

依赖引入

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

<dependency>  
    <groupId>org.apache.activemq</groupId>  
    <artifactId>activemq-pool</artifactId>  
</dependency>

application.properties 配置

# 整合 jms
spring.activemq.broker-url=tcp://10.11.124.102:61616

spring.activemq.user=admin
spring.activemq.password=admin

spring.activemq.pool.enabled=true
spring.activemq.pool.max-connections=100

程序启动类

  • 通过 @EnableJms 开启支持 jms
@EnableJms
@SpringBootApplication
public class QueueApplication {
    ……
}

服务层

接口设计( IProducerService )

public interface IProducerService {

    /**
     * Description: 指定消息队列,以及对应的消息
     * @param destination
     * @param message
     */
    public void sendMessage(Destination destination, final String message);

    /**
     * Description: 使用默认消息队列,发送消息
     * @param message
     */
    public void sendMessage(final String message);

}

具体实现类( ProducerServiceImpl )

@Service(value = "producerService")
public class ProducerServiceImpl implements IProducerService {

    @Autowired
    private JmsMessagingTemplate jmsTemplate;

    @Override
    public void sendMessage(Destination destination,    String message) {
        // TODO Auto-generated method stub
        jmsTemplate.convertAndSend(destination, message);

    }

    @Override
    public void sendMessage(String message) {
        // TODO Auto-generated method stub
        jmsTemplate.convertAndSend(this.queue, message);

    }

}

控制层( OrderController )

@RestController
@RequestMapping(value = "/api")
public class OrderController {

    @Autowired
    private IProducerService producerService;

    @GetMapping(value = "/order")
    public Object order(String msg) {
        Destination destination = new ActiveMQQueue("order.queue");
        producerService.sendMessage(destination, msg);
        return JsonData.buildSuccess();
    }

}

消费者( OrderConsumer )

@Component
public class OrderConsumer {

    @JmsListener(destination = "order.queue")
    public void receiveQueue(String text) {
        System.out.println("OrderConsumer 收到的消息:" + text);
    }

}

猜你喜欢

转载自blog.csdn.net/AnselLyy/article/details/81044320