Springboot 整合 Rabbitmq消息队列
一、创建SpringBoot项目,并引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
二、pom.xml配置
#配置rabbitMq 服务器 rabbitmq: host: 127.0.0.1 port: 5672 username: guest password: guest #虚拟host 可以不设置,使用server默认host virtual-host: / publisher-confirms: true publisher-returns: true listener: simple: acknowledge-mode: manual concurrency: 1 max-concurrency: 10 retry: enabled: true
三、普通工作队列模式
1、首先在工程中新建RabbitConfig
文件
1 import org.springframework.amqp.core.*; 2 import org.springframework.context.annotation.Bean; 3 import org.springframework.context.annotation.Configuration; 4 5 /** 6 * @author 7 * @date 8 * @description rabbitmq配置类 9 */ 10 @Configuration 11 public class RabbitConfig { 12 13 /** 14 * 定义队列名 15 */ 16 private final static String STRING = "string"; 17 18 19 /** 20 * 定义string队列 21 * @return 22 */ 23 @Bean 24 public Queue string() { 25 return new Queue(STRING); 26 27 }
2、创建生产者
1 import org.springframework.amqp.core.AmqpTemplate; 2 import org.springframework.beans.factory.annotation.Autowired; 3 import org.springframework.stereotype.Component; 4 5 import javax.xml.ws.Action; 6 import java.text.SimpleDateFormat; 7 import java.util.Date; 8 9 /** 10 * @author 11 * @date 12 * @description rabbit消息生产者 13 */ 14 @Component 15 public class RabbitProducer { 16 17 @Autowired 18 private AmqpTemplate rabbitTemplate; 19 20 public void stringSend() { 21 Date date = new Date(); 22 String dateString = new SimpleDateFormat("YYYY-mm-DD hh:MM:ss").format(date); 23 System.out.println("[string] send msg:" + dateString); 24 // 第一个参数为刚刚定义的队列名称 25 this.rabbitTemplate.convertAndSend("string", dateString); 26 } 27 }
3、创建消费者
1 import org.springframework.amqp.core.AmqpTemplate; 2 import org.springframework.amqp.rabbit.annotation.RabbitHandler; 3 import org.springframework.amqp.rabbit.annotation.RabbitListener; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.stereotype.Component; 6 7 /** 8 * @author 9 * @date 10 * @description rabbitmq消费者 @RabbitListener(queues = "simpleMsg") 监听名simpleMsg的队列 11 */ 12 @Component 13 @RabbitListener(queues = "string") 14 public class StringConsumer { 15 16 @Autowired private AmqpTemplate rabbitmqTemplate; 17 18 /** 19 * 消息消费 20 * @RabbitHandler 代表此方法为接受到消息后的处理方法 21 */ 22 @RabbitHandler 23 public void recieved(String msg) { 24 System.out.println("[string] recieved message:" + msg); 25 } 26 27 }
QQ群 :216868740
4、调用
1 @RestController 2 public class TestController { 3 4 @Autowired 5 private RabbitProducer producer; 6 7 @RequestMapping("/test") 8 public void test(){ 9 for (int i = 0; i < 10; i++) { 10 producer.stringSend(); 11 } 12 } 13 }