springboot 簡單整合rabbitmq
阿新 • • 發佈:2018-12-21
pom檔案新增:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
由於配置檔案是用的是apollo,所以引入apollo
<dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>0.8.0</version> </dependency>
使用apollo 只用在啟動類上加上
@EnableApolloConfig({"application", "***","****"})<!--自己在apollo中定義的名稱-->
定義一個類,配置mq:
@Configuration public class RabbitConfigure { public static final Config appConfiguration = ConfigService.getAppConfig(); // 佇列名稱 public final static String PAYMENT_QUEUE_MMMALL_QUEUE = appConfiguration.getProperty("payment_queue_MMMALL"); // 交換機名稱 public final static String PAYMENT_QUEUE_MMMALL_EXCHANGE = "payment-queue-mmmall-exchange"; // 繫結的值 public final static String PAYMENT_QUEUE_MMMALL_BIND_KEY = appConfiguration.getProperty("payment_queue_key_MMMALL"); @Bean Queue queue() { Map<String, Object> args = new HashMap<>(); args.put("x-dead-letter-exchange", "dlx-payment-queue-mmmall-exchange"); args.put("x-dead-letter-routing-key", "dlx_payment_queue_mmmall_key"); return new Queue(PAYMENT_QUEUE_MMMALL_QUEUE, true, false, false, args); } @Bean DirectExchange exchange() { return new DirectExchange(PAYMENT_QUEUE_MMMALL_EXCHANGE); } @Bean Binding binding(Queue queue, DirectExchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(PAYMENT_QUEUE_MMMALL_BIND_KEY ); } @Bean MessageConverter jackson2JsonMessageConverter() { return new Jackson2JsonMessageConverter(); } }
這樣就簡單的配置完成
生產:使用:我這裡發的是json,也可以使用bean物件
@Component public class NotifyMQ { private static final Logger logger = LoggerFactory.getLogger(NotifyMQ.class); @Autowired AmqpTemplate amqpTemplate; /** * * @param requestType:支付方式pay,refund * @param platformRequestNo:業務訂單號 */ public void send(String requestType, String platformRequestNo) { logger.info("傳送訊息佇列:requestType={},platformRequestNo={}",requestType,platformRequestNo); JSONObject jsonObject = new JSONObject(); jsonObject.put("requestType", requestType); jsonObject.put("platformRequestNo", platformRequestNo); amqpTemplate.convertAndSend(RabbitConfigure.PAYMENT_QUEUE_MMMALL_EXCHANGE, RabbitConfigure.PAYMENT_QUEUE_MMMALL_BIND_KEY, jsonObject.toString()); } }
消費bean:
@Component @RabbitListener(queues = "payment_queue_mmmall") public class ReceiveMsg { @RabbitHandler public void receiveMsg(String receivemsg) { System.out.println(receivemsg); } }
這樣簡單的rabbitmq就配置好了