- 首先你需要安裝RabbitMQ,安裝教程可百度查下資料即可,不做贅述,敬請諒解
- 啟動RabbitMQ
- RabbitMQ可以算是一個異步訊息佇列,在實際的開發專案中,一般是以
工具模塊的方式創建,像一些SpringBoot工程所需要的基本依賴都是會有的 - 說明:關鍵在于誰是訊息的生產者、訊息的消費者;另外還需要注意生產消費之間訊息型別的傳遞
- 創建一個maven工程,匯入RabbitMQ相關的依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
- 撰寫一個簡單的配置類,配置訊息轉換器
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
/**
* 配置訊息轉換器,默認是字串轉換器
* @return MessageConverter
*/
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
}
- 撰寫一個常量類
public class RabbitConstant {
/** 短信發送 */
public static final String EXCHANGE_DIRECT_MSM = "exchange.direct.msm";
public static final String ROUTING_MSM = "msm";
public static final String QUEUE_MSM = "queue.msm";
}
- 在撰寫一個簡單的生產訊息的封裝類
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RabbitService {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 生產訊息到RabbitMQ中
* @param exchange 交換機
* @param routingKey 路由Key
* @param message 任意型別的訊息
* @return boolean
*/
public boolean sendMessage(String exchange, String routingKey, Object message) {
rabbitTemplate.convertAndSend(exchange, routingKey, message);
return true;
}
}
- 雖說一個簡單的整合就這么幾步,主要還是實操示例,這里以
下單成功,通過手機發送訊息通知為示例 - 還需要在創建一個工程(接觸過微服務專案,很容易了解不同模塊有需要放在不同的服務下,便于管理)
- 既然涉及手機短信發訊息,可參考SpringBoot整合阿里云短信服務
- 在手機短信服務中匯入訊息佇列模塊,所以在原有的基礎上添加組態檔
#rabbitmq地址
spring.rabbitmq.host=your_ip
spring.rabbitmq.port=5672
spring.rabbitmq.username=your_username
spring.rabbitmq.password=your_password
- 封裝手機發送訊息,和手機發送驗證碼業務代碼相似,
@Service
public class MsmServiceImpl implements MsmService {
@Override
public boolean orderConfirm(Map<String, Object> param) {
if (StringUtils.isEmpty(param.get("phone"))) return false;
// 整合阿里云短信服務,設定相關引數
DefaultProfile profile = DefaultProfile.
getProfile(ConstantPropertiesUtils.REGION_ID,
ConstantPropertiesUtils.ACCESS_KEY,
ConstantPropertiesUtils.ACCESS_SECRET);
IAcsClient client = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(param.get("phone"));//接收短信的手機號碼
request.setSignName(ConstantPropertiesUtils.SIGN_NAME);//短信簽名名稱
request.setTemplateCode(ConstantPropertiesUtils.TEMPLATE_CODE);//短信模板CODE
// 使用json格式 {"msg":"下單成功"}
request.setTemplateParam(JSONObject.toJSONString(param));//短信模板變數對應的實際值
try {
SendSmsResponse response = client.getAcsResponse(request);
// 發送短信,盡量列印出來是否發送成功
new Gson().toJson(response);
} catch (ClientException e) {
e.printStackTrace();
return false;
}
return true;
}
}
- 在當前短信服務模塊中創建一個RabbitMQ訊息監聽(可以理解為訊息的消費者)
import com.rabbitmq.client.Channel;
import com.xsha.msg.service.MsgService;
import com.xsha.rabbit.constant.RabbitConstant;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MsgReceive {
@Autowired
private MsgService msgService;
/** 訊息監聽:監聽到RabbitMQ中有訊息就消費,并通過手機發送短信通知 */
@RabbitListener(bindings = @QueueBinding(
value = https://www.cnblogs.com/aitiknowledge/archive/2022/08/12/@Queue(value = RabbitConstant.QUEUE_MSM, durable ="true"),
exchange = @Exchange(value = https://www.cnblogs.com/aitiknowledge/archive/2022/08/12/RabbitConstant.EXCHANGE_DIRECT_MSM),
key = {RabbitConstant.ROUTING_MSM}
))
public void orderConfirm(Map param, Message message, Channel channel) {
msgService.orderConfirm(param);
}
}
- 由于涉及訂單,所以訂單是一個獨立的服務模塊,即匯入訊息佇列模塊,在原有的基礎上添加組態檔
#rabbitmq地址
spring.rabbitmq.host=your_ip
spring.rabbitmq.port=5672
spring.rabbitmq.username=your_username
spring.rabbitmq.password=your_password
- 在實際開發中,用戶下單并不會立即通知用戶下單成功,而是通過異步的方式稍后告知用戶下單成功,簡單示例,不可鉆牛角尖
- 生成訂單業務(不考慮庫存),就是訊息的生產者
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private RabbitService rabbitService;
@Override
public void saveOrder(String userId, String id) {
UserInfo userInfo = userInfoService.selectById(userId);
String phone = userInfo.getPhone();
// 短信資訊封裝(根據業務需求,封裝重要資訊)
Map<String,Object> param = new HashMap<String,Object>(){{
put("title", "訊息標題");
put("phone", phone);
put("message", "下單成功");
put("name", userInfo.getName());
put("currentTime", new DateTime().toString("yyyy-MM-dd HH:mm"));
}};
// 生產訊息
rabbitService.sendMessage(RabbitConstant.EXCHANGE_DIRECT_MSM, RabbitConstant.ROUTING_MSM, param);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/501689.html
標籤:其他
