1、创建一个配置类,这里根据enable变量判断是否开启mq配置
package com.lili.office.config;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
public class RabbitmqConfig {
@Value("${spring.rabbitmq.host:}")
private String rabbitmqHost;
public static boolean enable = false;
@PostConstruct
public void init() {
enable = StringUtils.isNotEmpty(rabbitmqHost);
}
public final static String QUEUE_NAME = "ly-jamiechyi_test";
@Bean
public Queue queue() {
return new Queue(QUEUE_NAME);
}
}
2、发送消息
@Autowired
private AmqpTemplate rabbitTemplate;
@GetMapping("/test1")
public void test1(){
if (RabbitmqConfig.enable){
// 发送一条消息
rabbitTemplate.convertAndSend(RabbitmqConfig.QUEUE_NAME,"2");
}
}
3、主动消费方式
if (RabbitmqConfig.enable){
// 接收一条消息
Object o = rabbitTemplate.receiveAndConvert(RabbitmqConfig.QUEUE_NAME);
// 其他逻辑
}
4、监听消息进行消费方式
@Component
@ConditionalOnProperty(name = "spring.rabbitmq.host")
public class MessageConsumer {
@RabbitListener(queues = RabbitmqConfig.QUEUE_NAME)
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
// 在这里编写处理消息的逻辑
}
}