rabbitmq五种模式详解(含实现代码) (2)

3.Work队列 3.1 编写工作配置 package com.gmtgo.demo.work; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author 大帅 */ @Configuration public class WorkQueueConfig { /** * 队列名. */ private final String work = "work_queue"; @Bean public Queue workQueue() { return new Queue(work); } } 3.2 编写生产者 package com.gmtgo.demo.work; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author 大帅 */ @Slf4j @Component public class WorkProducer { @Autowired private RabbitTemplate rabbitTemplate; public void sendMessage() { for (int i = 0; i < 10; i++) { String message = "工作消息" + i; log.info("我是生产信息:{}", message); rabbitTemplate.convertAndSend("work_queue", message); } } } 3.3 编写消费者1 package com.gmtgo.demo.work; import com.rabbitmq.client.Channel; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import java.io.IOException; /** * @author 大帅 */ @Slf4j @Component public class WorkConsumers1 { @RabbitListener(queues = "work_queue") public void readMessage(Message message, Channel channel) throws IOException { channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); log.info("我是消费信息1:{}", new String(message.getBody())); } } 3.4 编写消费者2 package com.gmtgo.demo.work; import com.rabbitmq.client.Channel; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import java.io.IOException; /** * @author 大帅 */ @Slf4j @Component public class WorkConsumers2 { @RabbitListener(queues = "work_queue") public void readMessage(Message message, Channel channel) throws IOException { channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); log.info("我是消费信息2:{}", new String(message.getBody())); } } 3.5 编写测试方法 package com.gmtgo.demo.work; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author 大帅 */ @RestController @RequestMapping(value = "rabbitMq") public class WorkRabbitMqController { @Autowired private WorkProducer workProducer; @RequestMapping(value = "workQueueTest") public String workQueueTest() { workProducer.sendMessage(); return "success"; } } 3.6 测试启动项目访问 workQueueTest

访问地址:8801/rabbitMq/workQueueTest

结果:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpgyzj.html