从实战的角度谈微服务(六):对于消息中间件RabbitMQ的基本使用
1、rabbitMQ在docker下的安装
https://www.rabbitmq.com/download.html
命令
docker run -d --hostname my-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3.7.15-management
访问管理界面(默认用户名密码为guest)
2、添加依赖jar
<!--rocketMQ 开始 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!--rocketMQ 结束-->
3、添加配置
spring:
rabbitmq:
host: 192.168.100.104
port: 5672
username: guest
password: guest
4、添加使用消息接收类
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @ desc:配置docker 虚拟机104IP的启动rabbitMQ
* @ Author :.
* @ Date :Created in 19:52 2019/6/17
*/
@Slf4j
@Component
public class MQReceiver {
//1.0,需要手动在管理创建队列
// @RabbitListener(queues = "myQueue")
//2.0可自动创建队列
// @RabbitListener(queuesToDeclare = @Queue("testQueue"))
//3.0 自动创建 Exchange和Queue绑定
@RabbitListener(bindings = @QueueBinding(
value = @Queue("myQueues"),
exchange = @Exchange("myExchanges")
))
public void process(String messgae){
log.info("==myQueue=== is:"+messgae);
}
}
5、消息发送测试
import com.gensoft.order.OrderApplicationTests;
import org.junit.Test;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.xml.ws.Action;
import java.util.Date;
/**
* @ desc:
* @ Author .
* @ Date :Created in 19:54 2019/6/17
*/
@Component
public class MQRecieverTest extends OrderApplicationTests {
@Autowired
private AmqpTemplate amqpTemplate;
@Test
public void send(){
amqpTemplate.convertAndSend("myQueues","now is"+new Date());
}
}
开发工作着,生活快乐着,留下总结,相互交流,共同进步