生产者
创建一个名为spring-boot-amop-provider的生产者项目
application.yml
spring:
application:
name: spring-boot-amqp
rabbitmq:
host: 192.168.25.143
port: 5672
username: rabbit
password: 123456
创建队列配置
package com.funtl.hello.rabbit.config;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfiguration {
@Bean
public Queue queue(){
return new Queue("helloRabbit");
}
}
创建消息提供者
package com.funtl.hello.rabbit;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class RabbitProvider {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(){
String content="Hello"+new Date();
System.out.println("Provider:"+content);
amqpTemplate.convertAndSend("helloRabbit", content);
}
}
创建测试类, 向消息队列发送消息
package com.funtl.hello.rabbit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes=HelloRabbitApplication.class)
public class HelloRabbitApplicationTests {
@Autowired
private RabbitProvider rabbitProvider;
@Test
public void contextLoads() {
for(int i=0; i<100; i++){
rabbitProvider.send();
}
}
}
从RabbitMQ的控制台可以看到, 消息已经发送到队列
消费者
package com.funtl.hello.rabbit;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues="helloRabbit")
public class RabbitConsumer {
@RabbitHandler
public void process(String content){
System.out.println("Consumer: "+content);
}
}
启动应用程序, 由于消费者监听了helloRabbit这个Queue, 所以消息队列里的消息会被消费
package com.funtl.hello.rabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloRabbitApplication {
public static void main(String[] args) {
SpringApplication.run(HelloRabbitApplication.class, args);
}
}
之后查看消息队列中的消息, 已经被成功消费