Docker安装RabbitMQ
1.导入依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-amqpartifactId>
dependency>
2.appllcation.properties配置
spring.rabbitmq.host=192.168.137.136
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=5672
3.主启动类
/**
* 自动配置
* RabbitAutoConfiguration
* ConnectionFactory连接工厂
* RabbitProperties 封装了RabbitMq相关配置
* RabbitTemplate给RabbitMQ发送和接收消息
* AmqpAdmin RabbitMQ系统管理功能组件
*/
@SpringBootApplication
@EnableRabbit //开启基于注解的rabbit
public class Springboot212RabbitmqApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot212RabbitmqApplication.class, args);
}
}
这里因为开发中我们常用json格式存储数据,而springboot默认是java序列化后存储
4.创建配置类自定义消息转换器:
/**
* 配置关于RabbitMq相关配置
*/
@Configuration
public class MyRabbitMQConfig {
//自定义消息转换器 json格式序列化
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
5.创建实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
private Integer id;
private String name;
private boolean flag;
}
6.使用springboot测试环境测试:
@SpringBootTest
class SpringbootRabbitmqApplicationTests {
@Autowired //操作发送消息 接收消息
private RabbitTemplate rabbitTemplate;
/**
* 发送点对点
*/
@Test
void contextLoads() {
//Message需要自己构造一个 定义消息体内容和消息头
// rabbitTemplate.send(exchange,routeKey,message);
//Object默认是消息体 只需传入要发送的对象就可以 默认java序列化给rabbitmq
HashMap<String, Object> map = new HashMap<>();
map.put("msg","这是我的第一个消息");
map.put("data", Arrays.asList(1,"yang",18,true));
rabbitTemplate.convertAndSend("exchange.direct","yang",map);
}
/**
* 接收消息
*/
@Test
void test01(){
//接收后消息就没有了
Object yang = rabbitTemplate.receiveAndConvert("yang");
System.out.println(yang);
}
/**
* 广播式
*/
@Test
void test02() {
User yang = new User(1, "yang", true);
rabbitTemplate.convertAndSend("exchange.fanout","", yang);
}
}
@Service
public class UserService {
/**
* 开启rabbitMQ监听
* 如果设置的消息队列,有消息进来就会执行该方法
*/
@RabbitListener(queues = "yang")
public void receive(User user){
System.out.println("添加了"+user);
}
@RabbitListener(queues = "yang.users")
public void receive02(Message message){
System.out.println(message.getBody()); //消息内容
System.out.println(message.getMessageProperties()); //消息头信息
}
}
@Autowired //管理创建删除交换器和消息队列
AmqpAdmin amqpAdmin;
@Test
void test03(){
//创建rabbitMQ的交换器 new FanoutExchange() / new TopicExchange()
amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
//创建消息队列 默认随便起个名字
amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true));
//将队列和交换器绑定起来
amqpAdmin.declareBinding(new Binding("amqpadmin.queue",
Binding.DestinationType.QUEUE,
"amqpadmin.exchange","amqp.haha",null));
//删除队列或者交换器
amqpAdmin.deleteExchange("amqpadmin.exchange");
amqpAdmin.deleteQueue("amqpadmin.queue");
}