持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第22天,点击查看活动详情
每日英语:
The moon is a friend for the lonesome to talk to.
翻译:月亮是孤独者的倾诉对象。 ——卡尔·桑德堡
退款申请状态通知
我们将退款申请结果发送到MQ,同时做一次退款申请记录,退款申请记录表如下:
CREATE TABLE `refund_log` (
`id` varchar(60) NOT NULL,
`order_no` varchar(60) NOT NULL COMMENT '订单号',
`out_refund_no` varchar(60) NOT NULL COMMENT '退款订单号(order_refund的id)',
`money` int(11) DEFAULT NULL COMMENT '退款金额',
`create_time` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1)Api
为上面表创建一下实体Bean,在mall-pay-api中创建com.xz.mall.pay.model.RefundLog
@Data
@AllArgsConstructor
@NoArgsConstructor
//MyBatisPlus表映射注解
@TableName(value = "refund_log")
public class RefundLog implements Serializable {
@TableId(type = IdType.ASSIGN_UUID)
private String id;
private String orderNo;
private String outRefundNo;
private Integer money;
private Date createTime;
}
2)Dao
在mall-pay-service中创建com.xz.mall.pay.mapper.RefundLogMapper
public interface RefundLogMapper extends BaseMapper<RefundLog> {
}
3)退款申请状态通知
mall-pay-service添加监听器com.xz.mall.pay.mq.RefundStatusTransactionListenerImpl
用于监听退款申请结果。
@Component
@RocketMQTransactionListener(txProducerGroup = "refundstatustx")
public class RefundStatusTransactionListenerImpl implements RocketMQLocalTransactionListener {
@Autowired
private RefundLogMapper refundLogMapper;
/***
* 发送prepare消息成功后回调该方法用于执行本地事务
* @param message:回传的消息,利用transactionId即可获取到该消息的唯一Id
* @param o:调用send方法时传递的参数,当send时候若有额外的参数可以传递到send方法中,这里能获取到
* @return
*/
@Override
public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
try {
//================本地事务操作开始=====================================
//将o转成Map
Map<String,String> resultMap = (Map<String, String>) o;
//添加退款日志记录
RefundLog refundLog = new RefundLog(
IdWorker.getIdStr(),
resultMap.get("out_trade_no"), //原订单号
resultMap.get("out_trade_no"), //退款订单号(order_refund的id)
Integer.valueOf(resultMap.get("refund_fee")), //退款金额
new Date()
);
int count = refundLogMapper.insert(refundLog);
//================本地事务操作结束=====================================
} catch (Exception e) {
//异常,消息回滚
e.printStackTrace();
return RocketMQLocalTransactionState.ROLLBACK;
}
return RocketMQLocalTransactionState.UNKNOWN;
}
/***
* 消息回查
* @param message
* @return
*/
@Override
public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
return RocketMQLocalTransactionState.COMMIT;
}
}
4)事务消息发送
修改com.xz.mall.pay.mq.RefundResultListener, 将退款申请结果推送到MQ,代码如下:
if(map!=null){
//执行退款申请
Map<String, String> resultMap = weixinPayService.refund(map);
//执行事务通知
Message message = MessageBuilder.withPayload(resultMap).build();
rocketMQTemplate.sendMessageInTransaction("refundstatustx",
"refundstatus",
message,
resultMap);
}
总结
本篇主要讲述了一下退款申请状态通知这一需求的具体代码实现。