本文共 1806 字,大约阅读时间需要 6 分钟。
1、安装rabbitmq
docker安装,拉取镜像docker pull rabbitmq:management创建容器并启动docker run -d --name rabbitmq --publish 5671:5671 --publish 5672:5672 --publish 4369:4369 --publish 25672:25672 --publish 15671:15671 --publish 15672:15672 rabbitmq:management管理地址: 用户名:guest 密码:guest2、配置springboot
(1)pom.xml添加依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency>(2)添加rabbit配置文件,配置server信息
import org.springframework.amqp.core.Queue;import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;import org.springframework.amqp.rabbit.connection.ConnectionFactory;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/**(3)创建生产者,循环下发四个任务,用sleep模拟任务处理时间,一个.代码任务处理1s的时长,分别有四个不同时长的任务下发
import org.springframework.amqp.core.AmqpTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/**(4)创建两个消费者Receiver1,Receiver2处理队列的任务
Receiver1:
import org.springframework.amqp.rabbit.annotation.RabbitHandler;import org.springframework.amqp.rabbit.annotation.RabbitListener;import org.springframework.stereotype.Component;/**Receiver2:
import org.springframework.amqp.rabbit.annotation.RabbitHandler;import org.springframework.amqp.rabbit.annotation.RabbitListener;import org.springframework.stereotype.Component;/**可以看到最先完成的消费者去执行下一个任务,是按任务时长执行,并不是按任务个数平分,防止消费者无意义的等待,提高效率。
查看rabbit的管理端http://localhost:15672/
可以看到已经生成队列至此整个任务完成!
转载于:https://blog.51cto.com/fengzhankui/2060275