欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Cloud 实践:ActiveMQ

程序员文章站 2022-04-30 15:49:29
...

本想用RabbitMQ,发现不是Java的,还得多装一个环境,还是用ActiveMQ吧。

依赖:

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

application.properties:

spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false

Producer:

@Component
public class Producer {

	@Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
	private JmsMessagingTemplate jmsTemplate;
	
	// 发送消息,destination是发送到的队列,message是待发送的消息
	public void sendMessage(Destination destination, final String message){
		jmsTemplate.convertAndSend(destination, message);
	}
	
}

测试:

@RestController
public class DemoController {

    @Autowired
    private Producer producer;

    @GetMapping("/message")
    public void send() {

		Destination destination = new ActiveMQQueue("mytest.queue");
		
		for(int i=0; i<10; i++){
			producer.sendMessage(destination, "new message!!!");
		}

    }
}

Consumer(可在另一个app):

@Component
public class Consumer {

	@JmsListener(destination = "mytest.queue")
	public void receiveQueue(String text) {
		System.out.println("Consumer receive:"+text);
	}

}