需要的依赖
<!-- rabbitmq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置文件 application.yml
spring:
rabbitmq:
host: 公网ip
username: 用户名
password: 密码
发送端
@Component
public class Sender {
@Resource
AmqpTemplate amqpTemplate;
public void sent(String msg){
amqpTemplate.convertAndSend("directExchange","com.product.sms",msg);
}
}
接收端
@Component
public class Receiver {
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(value="myDirect",autoDelete = "false"),
exchange=@Exchange(value="directExchange",type= ExchangeTypes.DIRECT),
key="com.product.sms"
)
)
public void onSms(String msg){
System.out.println("收到信息了:"+msg);
}
}
接收端注解如下
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(value="myDirect",autoDelete = "false"),
exchange=@Exchange(value="directExchange",type= ExchangeTypes.DIRECT),
key="com.product.sms"
)
)
测试
public void test01(){
while (true){
sender.sent("这是sender送出的第"+i+++"条消息");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|