- 首先你需要安装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
- 封装手机发送消息,和手机发送验证码业务代码相似。注意param变量
@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
// 这里的param变量中的键值需要和短信模板中设定的键值一致,否则发送不成功
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 = @Queue(value = RabbitConstant.QUEUE_MSM, durable = "true"),
exchange = @Exchange(value = RabbitConstant.EXCHANGE_DIRECT_MSM),
key = {RabbitConstant.ROUTING_MSM}
))
public void orderConfirm(Map<String, Object> 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);
}
}