rabbitmq与springboot整合
首先肯定得导入相应的jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
一、收集配置信息
application.properties文件如下:
server.port=8081
server.context-path=/
# redis配置信息
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=1
spring.redis.pool.max-total=200
spring.redis.pool.max-wait=5000
# 配置redis-cluster集群节点信息
spring.redis.cluster.nodes=192.168.47.102:8000,192.168.47.102:8001,192.168.47.102:8002
# rabbitmq配置信息,不能自定义key
spring.rabbitmq.host=192.168.47.102
spring.rabbitmq.port=5672
spring.rabbitmq.username=jtadmin
spring.rabbitmq.password=123456
spring.rabbitmq.virtual-host=/jt
二、声明对象,由框架管理
创建一个RabbitMQConfig类
package com.gykalc.rediscluster.configuration;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
/**
* 声明路由模式的交换机 交给框架管理
* @return
*/
@Bean
public DirectExchange getExchange() {
return new DirectExchange("springboot-direct");
}
/**
* 声明队列,如果同一个交换机有绑定队列,将会直接使用
* 没有绑定的,创建
* @return
*/
@Bean
public Queue getQueue() {
return new Queue("itemQueue");
}
/**
* 使用bind对象维护队列交换机的绑定
* @return
*/
@Bean
public Binding binding() {
return BindingBuilder.bind(getQueue()).to(getExchange()).with("item.add");
}
}
三、在Controller中测试生产者代码
package com.gykalc.rediscluster.controller;
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;
@RestController
public class RabbitMQController {
@Autowired
private AmqpTemplate rabbitMQTemplate;
/**
* 消息生产者
* @param msg
* @return
*/
@RequestMapping("itemAdd")
public String send(String msg) {
System.out.println("接收到消息:" + msg);
rabbitMQTemplate.convertAndSend("springboot-direct", "item.add", msg);
return "消息发送成功";
}
}
四、创建消费者监听消息队列
创建一个RabbitMQReceiver类
package com.gykalc.rediscluster.rabbitmq;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class RabbitMQReceiver {
@RabbitListener(queues = "itemQueue")
public void spendMsg(String msg) {
System.out.println("消费者获得了消息:" + msg);
}
}