title: rabbitmq
date: 2022-11-29 19:02:37
tags:
使用
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
加配置
spring:
rabbitmq:
host: 192.168.1.160
port: 5672
virtual-host: /mall
username: mall
password: mall
publisher-confirms: true #消息发送到交换器确认
publisher-returns: true #消息发送到队列确认
设置Vitual Hosts
添加配置类
- 队列
- 生产者sender
- 消费者eeceiver
@Configuration
public class SimpleRabbitConfig {
@Bean
public Queue hello() {
return new Queue("simple.hello");
}
@Bean
public SimpleSender simpleSender(){
return new SimpleSender();
}
@Bean
public SimpleReceiver simpleReceiver(){
return new SimpleReceiver();
}
}
生产者
public class SimpleSender {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleSender.class);
@Autowired
private RabbitTemplate template;
private static final String queueName = "simple.hello";
public void send() {
String message = "Hello World!";
this.template.convertAndSend(queueName, message);
LOGGER.info(" [x] Sent '{}'", message);
}
}
消费者
@RabbitListener(queues = "simple.hello")
public class SimpleReceiver {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleReceiver.class);
@RabbitHandler
public void receive(String in) {
LOGGER.info(" [x] Received '{}'", in);
}
}
其他地方使用时调用生产者的send方法即可
例如controller中
@Controller
public class RabbitController {
@Autowired
private SimpleSender simpleSender;
@RequestMapping(value = "/simple", method = RequestMethod.GET)
@ResponseBody
public String simpleTest() throws InterruptedException {
for(int i=0;i<10;i++){
simpleSender.send();
Thread.sleep(1000);
}
return "ok";
}
}
五种模式
简单模式
一个生产者,一个消费者,一个队列
上面那个例子就是简单模式