MessageUtils.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package com.uas.sso.util;
  2. import com.uas.message.mail.service.MailService;
  3. import com.uas.message.sms.service.SmsService;
  4. import com.uas.sso.entity.Setting;
  5. import com.uas.sso.service.SettingService;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Component;
  10. import javax.annotation.PostConstruct;
  11. import java.util.Map;
  12. /**
  13. * @author wangmh
  14. * @create 2018-06-05 17:17
  15. * @desc 消息工具类
  16. **/
  17. @Component
  18. public class MessageUtils {
  19. @Autowired
  20. private SmsService smsService;
  21. @Autowired
  22. private MailService mailService;
  23. @Autowired
  24. private SettingService settingService;
  25. private static MessageUtils messageUtils;
  26. protected final Logger logger = LoggerFactory.getLogger(MessageUtils.class);
  27. @PostConstruct
  28. public void init() {
  29. messageUtils = this;
  30. }
  31. /**
  32. * 发送短信
  33. * @param templateId 模板id
  34. * @param mobile 手机号
  35. * @param data 发送短信适配数据,按顺序添加
  36. */
  37. public static void sendSms(String templateId, String mobile, Object... data) {
  38. try {
  39. if (StringUtils.isEmpty(mobile)) {
  40. throw new RuntimeException("用户手机号不存在");
  41. }
  42. Setting smsTplId = messageUtils.settingService.findOne(templateId);
  43. if (StringUtils.isEmpty(smsTplId)) {
  44. throw new RuntimeException("模板不存在");
  45. }
  46. messageUtils.logger.warn("短信发送准备, 模板:{},手机号:{}", templateId, mobile);
  47. messageUtils.smsService.send(smsTplId.getValue(), mobile, data);
  48. messageUtils.logger.warn("短信发送完成, 模板:{},手机号:{}", templateId, mobile);
  49. } catch (Exception e) {
  50. messageUtils.logger.warn("短信发送失败,{}, 模板:{},手机号:{}", e.getMessage(), templateId, mobile);
  51. }
  52. }
  53. /**
  54. * 发送邮件
  55. * @param templateId 模板id
  56. * @param email 邮箱
  57. * @param data 发送邮件适配数据,以键值对的形式添加
  58. */
  59. public static void sendEmail(String templateId, String email, Map<String, Object> data) {
  60. try {
  61. if (StringUtils.isEmpty(email)) {
  62. throw new RuntimeException("邮箱不存在");
  63. }
  64. Setting mailTplId = messageUtils.settingService.findOne(templateId);
  65. if (StringUtils.isEmpty(mailTplId)) {
  66. throw new RuntimeException("模板不存在");
  67. }
  68. messageUtils.mailService.send(mailTplId.getValue(), email, data);
  69. } catch (Exception e) {
  70. messageUtils.logger.warn("邮箱发送失败, {},模板:{},邮箱:{}", e.getMessage(), templateId, email);
  71. }
  72. }
  73. }