建造者模式构建消息模板,动态参数

原创
2018/12/05 18:36
阅读数 36

建造者模式,模板方法少模板,实现。

发送消息通知

    // 发送消息通知
    public void sendAppealNotice(Long userId, NotifyTypeEnum template, Long orderNo, BigDecimal usdtNum) {
        Date date = DateUtils.currentDate();
        String dateStr=DateUtils.getPatternDate(date, "yyyy-MM-dd HH:mm:ss");
        NotifyDTO dto = new NotifyDTO.NotifyDTOBuilder().build(userId, template, orderNo, dateStr, BigDecimalUtil.format(usdtNum,2)).build();
        try {
            log.info("发送消息通知 method:sendAppealNotice,param:{}",dto.toString());
            ResponseResult result = smsClient.sendNotice(dto);
            if(null!=result){
                log.info("结果:",result.toString());
            }
        } catch (Exception e) {
            log.error("发送{}消息通知错误,错误信息{}" ,template, e.getMessage());
        }

    }

 

建造者模式

@Data
public class NotifyDTO implements Serializable {
    private static final long serialVersionUID = -4319190926774514600L;
    private Long userId;
    private String template;
    private String params;

    public static class NotifyDTOBuilder {
        Long userId;
        NotifyTypeEnum template;
        String date;
        BigDecimal usdtNum;
        Long orderNo;

        public NotifyDTOBuilder build(Long userId, NotifyTypeEnum template, Long orderNo, String date, BigDecimal usdtNum) {
            this.userId = userId;
            this.template = template;
            this.orderNo = orderNo;
            this.date = date;
            this.usdtNum = usdtNum;
            return this;
        }

        public NotifyDTO build() {
            return new NotifyDTO(this);
        }

        public String getParams() {
            JSONObject json = new JSONObject();
            if (!StringUtils.isEmpty(date)) {
                json.put("date", date);
            }
            if (!StringUtils.isEmpty(orderNo)) {
                json.put("orderNo", orderNo);
            }
            if (!StringUtils.isEmpty(usdtNum)) {
                json.put("usdtNum", usdtNum);
            }
            try {
                return URLEncoder.encode(json.toString(),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return "";
        }

    }

    public NotifyDTO(NotifyDTOBuilder b) {
        this.userId = b.userId;
        this.template = b.template.name();
        this.params = b.getParams();
    }

 

消息模板参数不固定

您买入${usdtNum}个USDT的订单,由对方发起的申诉于${date}已处理,订单已成功完成,如有问题请与客服联系。	
You buy the order of ${usdtNum} USDT, the complaint initiated by the other party has been processed in ${date}, and the order has been successfully completed. If you have any questions, please contact the customer service.	
您于${date}发起的OTC交易订单${orderNo}已成功买入,请注意查看。	
Your OTC order ${orderNo} has been successfully buy the currencies at ${date}. Please check.	
您于${date}发起的OTC交易订单${orderNo}已成功卖出,请注意查看。	
Your OTC order ${orderNo} has been successfully sell the currencies at ${date}. Please check.	
您的 ${amount} 已于 ${date} 成功解冻,请注意查看。	
您的 ${amount} 已于 ${date} 成功解冻,请注意查看。	
您的${activityEN}奖励 ${amount} 已于 ${date} 到账您的币币钱包,请注意查收。	
Your ${activityUS} reward: ${amount} has arrived at ${date} your coin wallet, please pay attention to check.	

分别发给买卖

 

消息服务解析

@Override
public int insertNotify(NotifyTO notifyTO) {
    NotifyTypeEnum byTemplate = NotifyTypeEnum.getByTemplate(notifyTO.getTemplate());
    if (byTemplate == null || byTemplate.getCode() <= 0) {
        log.error("param template is illegal");
        return -1;
    }
    List<NotifyTemplate> templates =  notifyTemplateMapper.findTemplateByType(byTemplate.getCode());
    List<Notify> notifies = templates.stream().map(x -> {
        Notify notify = notifyTO.transToNotify();
        String msg = buildMsgByTemplate(x, notifyTO.getParams());
        notify.setMsg(msg);
        notify.setLanguage(x.getLanguage());
        notify.setTitle(x.getTitle());
        return notify;
    }).collect(Collectors.toList());
    return notifyMapper.batchInsert(notifies);

}

 

解析模板替换

private String buildMsgByTemplate(NotifyTemplate template, String paramStr) {
    String fields = template.getFields();

    String params = Decoders.urlDecode(paramStr);
    JSONObject jsonObject = JSONObject.parseObject(params);
    while (fields.contains("${")) {
        Matcher matcher = PARAM_PATTERN.matcher(fields);
        if(matcher.find()) {
            String ele = matcher.group(1);
            if(jsonObject.containsKey(ele)) {
                fields = fields.replaceFirst("\\$\\{"+ele+"\\}", jsonObject.getString(ele));
            }else {
                throw new SmsException("template can not be converted");
            }
        }
    }
    log.info(fields);
    return fields;
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部