SpringBoot整合RabbitMQ--發佈訂閱模式

生產者

Maven環境依賴

		<!-- springboot-web組件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 添加springboot對amqp的支持 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>

application.yml 配置信息

spring:
  rabbitmq:
  ####連接地址
    host: 127.0.0.1
   ####端口號   
    port: 5672
   ####賬號 
    username: guest
   ####密碼  
    password: guest
   ### 地址
    virtual-host: /admin_host

 

交換機綁定隊列

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

//Fanout 類型 發佈訂閱模式
@Component
public class FanoutConfig {

	// 郵件隊列
	private String FANOUT_EMAIL_QUEUE = "fanout_email_queue";

	// 短信隊列
	private String FANOUT_SMS_QUEUE = "fanout_sms_queue";
	// fanout 交換機
	private String EXCHANGE_NAME = "fanoutExchange";

	// 1.定義郵件隊列
	@Bean
	public Queue fanOutEamilQueue() {
		return new Queue(FANOUT_EMAIL_QUEUE);
	}

	// 2.定義短信隊列
	@Bean
	public Queue fanOutSmsQueue() {
		return new Queue(FANOUT_SMS_QUEUE);
	}

	// 2.定義交換機
	@Bean
	FanoutExchange fanoutExchange() {
		return new FanoutExchange(EXCHANGE_NAME);
	}

	// 3.隊列與交換機綁定郵件隊列
	@Bean
	Binding bindingExchangeEamil(Queue fanOutEamilQueue, FanoutExchange fanoutExchange) {
		return BindingBuilder.bind(fanOutEamilQueue).to(fanoutExchange);
	}

	// 4.隊列與交換機綁定短信隊列
	@Bean
	Binding bindingExchangeSms(Queue fanOutSmsQueue, FanoutExchange fanoutExchange) {
		return BindingBuilder.bind(fanOutSmsQueue).to(fanoutExchange);
	}
}

生產者投遞消息

import java.util.UUID;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

@Component
public class FanoutProducer {
	@Autowired
	private AmqpTemplate amqpTemplate;

	public void send(String queueName) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("email", "[email protected]");
		jsonObject.put("timestamp", System.currentTimeMillis());
		String jsonString = jsonObject.toJSONString();
		System.out.println("jsonString:" + jsonString);
		// 設置消息唯一id 保證每次重試消息id唯一
		Message message = MessageBuilder.withBody(jsonString.getBytes())
				.setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
				.setMessageId(UUID.randomUUID() + "").build();
		amqpTemplate.convertAndSend(queueName, message);
	}
}

 

控制層調用代碼

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.itmayiedu.rabbitmq.FanoutProducer;

@RestController
public class ProducerController {
	@Autowired
	private FanoutProducer fanoutProducer;

	@RequestMapping("/sendFanout")
	public String sendFanout(String queueName) {
		fanoutProducer.send(queueName);
		return "success";
	}
}

消費者

Maven環境依賴

		<!-- springboot-web組件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 添加springboot對amqp的支持 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<!--fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.49</version>
		</dependency>

 

application.yml

spring:
  rabbitmq:
  ####連接地址
    host: 127.0.0.1
   ####端口號   
    port: 5672
   ####賬號 
    username: guest
   ####密碼  
    password: guest
   ### 地址
    virtual-host: /admin_host
    listener: 
      simple:
        retry:
        ####開啓消費者異常重試
          enabled: true
         ####最大重試次數
          max-attempts: 5
        ####重試間隔次數
          initial-interval: 2000
        ####開啓手動ack  
        acknowledge-mode: manual 

 

郵件消費者:

import java.util.Map;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.itmayiedu.rabbitmq.utils.HttpClientUtils;
import com.rabbitmq.client.Channel;

//郵件隊列
@Component
public class FanoutEamilConsumer {
	// @RabbitListener(queues = "fanout_email_queue")
	// public void process(String msg) throws Exception {
	// System.out.println("郵件消費者獲取生產者消息msg:" + msg);
	// JSONObject jsonObject = JSONObject.parseObject(msg);
	// // 獲取email參數
	// String email = jsonObject.getString("email");
	// // 請求地址
	// String emailUrl = "http://127.0.0.1:8083/sendEmail?email=" + email;
	// JSONObject result = HttpClientUtils.httpGet(emailUrl);
	// if (result == null) {
	// // 因爲網絡原因,造成無法訪問,繼續重試
	// throw new Exception("調用接口失敗!");
	// }
	// System.out.println("執行結束....");
	//
	// }

	// @RabbitListener(queues = "fanout_email_queue")
	// public void process(Message message) throws Exception {
	// // 獲取消息Id
	// String messageId = message.getMessageProperties().getMessageId();
	// String msg = new String(message.getBody(), "UTF-8");
	// System.out.println("郵件消費者獲取生產者消息" + "messageId:" + messageId + ",消息內容:" +
	// msg);
	// JSONObject jsonObject = JSONObject.parseObject(msg);
	// // 獲取email參數
	// String email = jsonObject.getString("email");
	// // 請求地址
	// String emailUrl = "http://127.0.0.1:8083/sendEmail?email=" + email;
	// JSONObject result = HttpClientUtils.httpGet(emailUrl);
	// if (result == null) {
	// // 因爲網絡原因,造成無法訪問,繼續重試
	// throw new Exception("調用接口失敗!");
	// }
	// System.out.println("執行結束....");
	// }

	@RabbitListener(queues = "fanout_email_queue")
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		// 獲取消息Id
		String messageId = message.getMessageProperties().getMessageId();
		String msg = new String(message.getBody(), "UTF-8");
		System.out.println("郵件消費者獲取生產者消息" + "messageId:" + messageId + ",消息內容:" + msg);
		JSONObject jsonObject = JSONObject.parseObject(msg);
		// 獲取email參數
		String email = jsonObject.getString("email");
		// 請求地址
		String emailUrl = "http://127.0.0.1:8083/sendEmail?email=" + email;
		JSONObject result = HttpClientUtils.httpGet(emailUrl);
		if (result == null) {
			// 因爲網絡原因,造成無法訪問,繼續重試
			throw new Exception("調用接口失敗!");
		}
		// // 手動ack
		Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
		// 手動簽收
		channel.basicAck(deliveryTag, false);
		System.out.println("執行結束....");
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章