配置pom包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置文件
配置rabbitmq的地址、端口、账号密码
spring.application.name=Spring-boot-rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
队列配置
@Configuration
public class RabbitConfig {
@Bean
public Queue Queue() {
return new Queue("hello");
}
}
发送消息
@Component
public class HelloSend {
@Autowired
private AmqpTemplate rabbitAmqpTemplate;
public void send() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String context = "hello" + sdf.format(new Date());
System.out.println("Sender : " + context);
this.rabbitAmqpTemplate.convertAndSend("hello", context);
}
}
接收消息
@Component
@RabbitListener(queues = "hello")
public class HelloReceiver {
@RabbitHandler
public void process(String hello) {
System.out.println("Receiver : " + hello);
}
}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitMqHelloTest {
@Autowired
private HelloSender helloSender;
@Test
public void hello() throws Exception {
helloSender.send();
}
}
如果遇到:SimpleMessageConverter only supports String, byte[] and Serializable payloads, received:com.example.springBoot.pojo.User 问题
把需要传输的对象实现序列化接口就好了