1. 短信和邮件的账号信息抽取到apollo

2. http接口更改
pull/4/head
3y 3 years ago
parent f419ea3b0e
commit b4adb7d58e

@ -30,12 +30,8 @@ public class SmsParam {
private String content; private String content;
/** /**
* Id *
*/ */
private Integer supplierId; private Integer sendAccount;
/**
*
*/
private String supplierName;
} }

@ -0,0 +1,47 @@
package com.java3y.austin.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
*
*
* [{"sms_10":{"url":"sms.tencentcloudapi.com","region":"ap-guangzhou","secretId":"AKIDhDUUDfffffMEqBF1WljQq","secretKey":"B4h39yWnfffff7D2btue7JErDJ8gxyi","smsSdkAppId":"140025","templateId":"11897","signName":"Java3y公众号","supplierId":10,"supplierName":"腾讯云"}}]
*
* @author 3y
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TencentSmsParam {
/**
* api
*/
private String url;
private String region ;
/**
*
*/
private String secretId;
private String secretKey;
private String smsSdkAppId;
private String templateId;
private String signName;
/**
* Id
*/
private Integer supplierId;
/**
*
*/
private String supplierName;
}

@ -1,18 +1,17 @@
package com.java3y.austin.handler; package com.java3y.austin.handler;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil; import cn.hutool.extra.mail.MailUtil;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.java3y.austin.domain.AnchorInfo;
import com.java3y.austin.domain.TaskInfo; import com.java3y.austin.domain.TaskInfo;
import com.java3y.austin.dto.ContentModel;
import com.java3y.austin.dto.EmailContentModel; import com.java3y.austin.dto.EmailContentModel;
import com.java3y.austin.enums.AnchorState;
import com.java3y.austin.enums.ChannelType; import com.java3y.austin.enums.ChannelType;
import com.java3y.austin.utils.LogUtils; import com.java3y.austin.utils.AccountUtils;
import com.sun.mail.util.MailSSLSocketFactory; import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
@ -24,6 +23,12 @@ import org.springframework.stereotype.Component;
@Slf4j @Slf4j
public class EmailHandler extends Handler { public class EmailHandler extends Handler {
private static final String EMAIL_ACCOUNT_KEY = "emailAccount";
private static final String PREFIX = "email_";
@Autowired
private AccountUtils accountUtils;
public EmailHandler() { public EmailHandler() {
channelCode = ChannelType.EMAIL.getCode(); channelCode = ChannelType.EMAIL.getCode();
} }
@ -31,7 +36,7 @@ public class EmailHandler extends Handler {
@Override @Override
public boolean handler(TaskInfo taskInfo) { public boolean handler(TaskInfo taskInfo) {
EmailContentModel emailContentModel = (EmailContentModel) taskInfo.getContentModel(); EmailContentModel emailContentModel = (EmailContentModel) taskInfo.getContentModel();
MailAccount account = getAccount(); MailAccount account = getAccountConfig(taskInfo.getSendAccount());
try { try {
MailUtil.send(account, taskInfo.getReceiver(), emailContentModel.getTitle(), MailUtil.send(account, taskInfo.getReceiver(), emailContentModel.getTitle(),
emailContentModel.getContent(), true, null); emailContentModel.getContent(), true, null);
@ -42,27 +47,22 @@ public class EmailHandler extends Handler {
return true; return true;
} }
/** /**
* *
*
* @return * @return
*/ */
private MailAccount getAccount() { private MailAccount getAccountConfig(Integer sendAccount) {
MailAccount account = new MailAccount(); MailAccount account = accountUtils.getAccount(sendAccount, EMAIL_ACCOUNT_KEY, PREFIX, new MailAccount());
try { try {
account.setHost("smtp.qq.com").setPort(465);
account.setUser("403686131@qq.com").setPass("//TODO").setAuth(true);
account.setFrom("403686131@qq.com");
MailSSLSocketFactory sf = new MailSSLSocketFactory(); MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true); sf.setTrustAllHosts(true);
account.setStarttlsEnable(true).setSslEnable(true).setCustomProperty("mail.smtp.ssl.socketFactory", sf); account.setAuth(true).setStarttlsEnable(true).setSslEnable(true).setCustomProperty("mail.smtp.ssl.socketFactory", sf);
account.setTimeout(25000).setConnectionTimeout(25000); account.setTimeout(25000).setConnectionTimeout(25000);
} catch (Exception e) { } catch (Exception e) {
log.error("EmailHandler#getAccount fail!{}", Throwables.getStackTraceAsString(e)); log.error("EmailHandler#getAccount fail!{}", Throwables.getStackTraceAsString(e));
} }
return account; return account;
} }
} }

@ -5,15 +5,12 @@ import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.java3y.austin.dao.SmsRecordDao; import com.java3y.austin.dao.SmsRecordDao;
import com.java3y.austin.domain.AnchorInfo;
import com.java3y.austin.domain.SmsParam; import com.java3y.austin.domain.SmsParam;
import com.java3y.austin.domain.SmsRecord; import com.java3y.austin.domain.SmsRecord;
import com.java3y.austin.domain.TaskInfo; import com.java3y.austin.domain.TaskInfo;
import com.java3y.austin.dto.SmsContentModel; import com.java3y.austin.dto.SmsContentModel;
import com.java3y.austin.enums.AnchorState;
import com.java3y.austin.enums.ChannelType; import com.java3y.austin.enums.ChannelType;
import com.java3y.austin.script.SmsScript; import com.java3y.austin.script.SmsScript;
import com.java3y.austin.utils.LogUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -46,8 +43,8 @@ public class SmsHandler extends Handler {
.phones(taskInfo.getReceiver()) .phones(taskInfo.getReceiver())
.content(getSmsContent(taskInfo)) .content(getSmsContent(taskInfo))
.messageTemplateId(taskInfo.getMessageTemplateId()) .messageTemplateId(taskInfo.getMessageTemplateId())
.supplierId(10) .sendAccount(taskInfo.getSendAccount())
.supplierName("腾讯云通知类消息渠道").build(); .build();
try { try {
List<SmsRecord> recordList = smsScript.send(smsParam); List<SmsRecord> recordList = smsScript.send(smsParam);
if (!CollUtil.isEmpty(recordList)) { if (!CollUtil.isEmpty(recordList)) {

@ -1,8 +1,7 @@
package com.java3y.austin.script; package com.java3y.austin.script;
import com.java3y.austin.domain.SmsRecord;
import com.java3y.austin.domain.SmsParam; import com.java3y.austin.domain.SmsParam;
import com.tencentcloudapi.common.exception.TencentCloudSDKException; import com.java3y.austin.domain.SmsRecord;
import java.util.List; import java.util.List;
@ -15,7 +14,8 @@ public interface SmsScript {
/** /**
* *
* @param smsParam *
* @param smsParam
* @return * @return
*/ */
List<SmsRecord> send(SmsParam smsParam) throws Exception; List<SmsRecord> send(SmsParam smsParam) throws Exception;

@ -3,14 +3,13 @@ package com.java3y.austin.script;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import com.java3y.austin.constant.AustinConstant; import com.java3y.austin.constant.AustinConstant;
import com.java3y.austin.domain.SmsParam; import com.java3y.austin.domain.SmsParam;
import com.java3y.austin.domain.SmsRecord; import com.java3y.austin.domain.SmsRecord;
import com.java3y.austin.domain.TencentSmsParam;
import com.java3y.austin.enums.SmsStatus; import com.java3y.austin.enums.SmsStatus;
import com.java3y.austin.utils.AccountUtils;
import com.tencentcloudapi.common.Credential; import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile; import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile; import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient; import com.tencentcloudapi.sms.v20210111.SmsClient;
@ -18,7 +17,7 @@ import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse; import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus; import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
@ -37,42 +36,24 @@ import java.util.List;
public class TencentSmsScript implements SmsScript { public class TencentSmsScript implements SmsScript {
private static final Integer PHONE_NUM = 11; private static final Integer PHONE_NUM = 11;
private static final String SMS_ACCOUNT_KEY = "smsAccount";
private static final String PREFIX = "sms_";
/** @Autowired
* api private AccountUtils accountUtils;
*/
private static final String URL = "sms.tencentcloudapi.com";
private static final String REGION = "ap-guangzhou";
/**
*
*/
@Value("${tencent.sms.account.secret-id}")
private String SECRET_ID;
@Value("${tencent.sms.account.secret-key}")
private String SECRET_KEY;
@Value("${tencent.sms.account.sms-sdk-app-id}")
private String SMS_SDK_APP_ID;
@Value("${tencent.sms.account.template-id}")
private String TEMPLATE_ID;
@Value("${tencent.sms.account.sign_name}")
private String SIGN_NAME;
@Override @Override
public List<SmsRecord> send(SmsParam smsParam) throws TencentCloudSDKException { public List<SmsRecord> send(SmsParam smsParam) throws Exception {
TencentSmsParam tencentSmsParam = accountUtils.getAccount(smsParam.getSendAccount(), SMS_ACCOUNT_KEY, PREFIX, TencentSmsParam.builder().build());
SmsClient client = init(); SmsClient client = init(tencentSmsParam);
SendSmsRequest request = assembleReq(smsParam); SendSmsRequest request = assembleReq(smsParam,tencentSmsParam);
SendSmsResponse response = client.SendSms(request); SendSmsResponse response = client.SendSms(request);
return assembleSmsRecord(smsParam,response); return assembleSmsRecord(smsParam, response,tencentSmsParam);
} }
private List<SmsRecord> assembleSmsRecord(SmsParam smsParam, SendSmsResponse response) {
private List<SmsRecord> assembleSmsRecord(SmsParam smsParam, SendSmsResponse response, TencentSmsParam tencentSmsParam) {
if (response == null || ArrayUtil.isEmpty(response.getSendStatusSet())) { if (response == null || ArrayUtil.isEmpty(response.getSendStatusSet())) {
return null; return null;
} }
@ -88,8 +69,8 @@ public class TencentSmsScript implements SmsScript {
.sendDate(Integer.valueOf(DateUtil.format(new Date(), AustinConstant.YYYYMMDD))) .sendDate(Integer.valueOf(DateUtil.format(new Date(), AustinConstant.YYYYMMDD)))
.messageTemplateId(smsParam.getMessageTemplateId()) .messageTemplateId(smsParam.getMessageTemplateId())
.phone(Long.valueOf(phone)) .phone(Long.valueOf(phone))
.supplierId(smsParam.getSupplierId()) .supplierId(tencentSmsParam.getSupplierId())
.supplierName(smsParam.getSupplierName()) .supplierName(tencentSmsParam.getSupplierName())
.seriesId(sendStatus.getSerialNo()) .seriesId(sendStatus.getSerialNo())
.chargingNum(Math.toIntExact(sendStatus.getFee())) .chargingNum(Math.toIntExact(sendStatus.getFee()))
.status(SmsStatus.SEND_SUCCESS.getCode()) .status(SmsStatus.SEND_SUCCESS.getCode())
@ -106,13 +87,13 @@ public class TencentSmsScript implements SmsScript {
/** /**
* *
*/ */
private SendSmsRequest assembleReq(SmsParam smsParam) { private SendSmsRequest assembleReq(SmsParam smsParam, TencentSmsParam account) {
SendSmsRequest req = new SendSmsRequest(); SendSmsRequest req = new SendSmsRequest();
String[] phoneNumberSet1 = smsParam.getPhones().toArray(new String[smsParam.getPhones().size() - 1]); String[] phoneNumberSet1 = smsParam.getPhones().toArray(new String[smsParam.getPhones().size() - 1]);
req.setPhoneNumberSet(phoneNumberSet1); req.setPhoneNumberSet(phoneNumberSet1);
req.setSmsSdkAppId(SMS_SDK_APP_ID); req.setSmsSdkAppId(account.getSmsSdkAppId());
req.setSignName(SIGN_NAME); req.setSignName(account.getSignName());
req.setTemplateId(TEMPLATE_ID); req.setTemplateId(account.getTemplateId());
String[] templateParamSet1 = {smsParam.getContent()}; String[] templateParamSet1 = {smsParam.getContent()};
req.setTemplateParamSet(templateParamSet1); req.setTemplateParamSet(templateParamSet1);
req.setSessionContext(IdUtil.fastSimpleUUID()); req.setSessionContext(IdUtil.fastSimpleUUID());
@ -121,14 +102,15 @@ public class TencentSmsScript implements SmsScript {
/** /**
* client * client
* @param account
*/ */
private SmsClient init() { private SmsClient init(TencentSmsParam account) {
Credential cred = new Credential(SECRET_ID, SECRET_KEY); Credential cred = new Credential(account.getSecretId(), account.getSecretKey());
HttpProfile httpProfile = new HttpProfile(); HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint(URL); httpProfile.setEndpoint(account.getUrl());
ClientProfile clientProfile = new ClientProfile(); ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile); clientProfile.setHttpProfile(httpProfile);
SmsClient client = new SmsClient(cred, REGION, clientProfile); SmsClient client = new SmsClient(cred, account.getUrl(), clientProfile);
return client; return client;
} }

@ -41,6 +41,7 @@ public class DeduplicationRuleService {
private Config config; private Config config;
public void duplication(TaskInfo taskInfo) { public void duplication(TaskInfo taskInfo) {
// 配置示例:{"contentDeduplication":{"num":1,"time":300},"frequencyDeduplication":{"num":5}}
JSONObject property = JSON.parseObject(config.getProperty(DEDUPLICATION_RULE_KEY, AustinConstant.APOLLO_DEFAULT_VALUE_JSON_OBJECT)); JSONObject property = JSON.parseObject(config.getProperty(DEDUPLICATION_RULE_KEY, AustinConstant.APOLLO_DEFAULT_VALUE_JSON_OBJECT));
JSONObject contentDeduplication = property.getJSONObject(CONTENT_DEDUPLICATION); JSONObject contentDeduplication = property.getJSONObject(CONTENT_DEDUPLICATION);
JSONObject frequencyDeduplication = property.getJSONObject(FREQUENCY_DEDUPLICATION); JSONObject frequencyDeduplication = property.getJSONObject(FREQUENCY_DEDUPLICATION);

@ -28,8 +28,10 @@ public class DiscardMessageService {
* @return * @return
*/ */
public boolean isDiscard(TaskInfo taskInfo) { public boolean isDiscard(TaskInfo taskInfo) {
// 配置示例: ["1","2"]
JSONArray array = JSON.parseArray(config.getProperty(DISCARD_MESSAGE_KEY, JSONArray array = JSON.parseArray(config.getProperty(DISCARD_MESSAGE_KEY,
AustinConstant.APOLLO_DEFAULT_VALUE_JSON_ARRAY)); AustinConstant.APOLLO_DEFAULT_VALUE_JSON_ARRAY));
if (array.contains(String.valueOf(taskInfo.getMessageTemplateId()))) { if (array.contains(String.valueOf(taskInfo.getMessageTemplateId()))) {
LogUtils.print(AnchorInfo.builder().businessId(taskInfo.getBusinessId()).ids(taskInfo.getReceiver()).state(AnchorState.DISCARD.getCode()).build()); LogUtils.print(AnchorInfo.builder().businessId(taskInfo.getBusinessId()).ids(taskInfo.getReceiver()).state(AnchorState.DISCARD.getCode()).build());
return true; return true;

@ -1,7 +1,9 @@
package com.java3y.austin.domain; package com.java3y.austin.domain;
import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
/** /**
@ -10,6 +12,8 @@ import lombok.experimental.Accessors;
*/ */
@Data @Data
@Accessors(chain = true) @Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class SendRequest { public class SendRequest {
/** /**

@ -0,0 +1,40 @@
package com.java3y.austin.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.java3y.austin.constant.AustinConstant;
import org.springframework.stereotype.Component;
/**
*
*
* @author 3y
*/
@Component
public class AccountUtils {
@ApolloConfig("boss.austin")
private Config config;
/**
* [{"sms_10":{"url":"sms.tencentcloudapi.com","region":"ap-guangzhou","secretId":"AKIDhDUUDfffffMEqBF1WljQq","secretKey":"B4h39yWnfffff7D2btue7JErDJ8gxyi","smsSdkAppId":"140025","templateId":"11897","signName":"Java3y公众号","supplierId":10,"supplierName":"腾讯云"}}]
* [{"email_10":{"host":"smtp.qq.com","port":465,"user":"403686131@qq.com","pass":"","from":"403686131@qq.com"}}]
*/
public <T> T getAccount(Integer sendAccount, String apolloKey, String prefix, T t) {
String accountValues = config.getProperty(apolloKey, AustinConstant.APOLLO_DEFAULT_VALUE_JSON_ARRAY);
JSONArray jsonArray = JSON.parseArray(accountValues);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Object object = jsonObject.getObject(prefix + sendAccount, t.getClass());
if (object != null) {
return (T) object;
}
}
return null;
}
}

@ -1,17 +1,13 @@
package com.java3y.austin.controller; package com.java3y.austin.controller;
import com.java3y.austin.domain.MessageParam;
import com.java3y.austin.domain.SendRequest; import com.java3y.austin.domain.SendRequest;
import com.java3y.austin.domain.SendResponse; import com.java3y.austin.domain.SendResponse;
import com.java3y.austin.enums.BusinessCode;
import com.java3y.austin.service.SendService; import com.java3y.austin.service.SendService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/** /**
* @author * @author
*/ */
@ -22,35 +18,14 @@ public class SendController {
@Autowired @Autowired
private SendService sendService; private SendService sendService;
/**
*
* @return
*/
@GetMapping("/sendSmsTest")
public SendResponse sendSmsTest(String receiver, Long templateId) {
/** /**
*
* *
* messageTemplate Id 1 * @return
* {"auditStatus":10,"auditor":"yyyyyyz","created":1636978066,"creator":"yyyyc","deduplicationTime":1,"expectPushTime":"0","flowId":"yyyy","id":1,"idType":30,"isDeleted":0,"isNightShield":0,"msgContent":"{\"content\":\"{$contentValue}\"}","msgStatus":10,"msgType":10,"name":"test短信","proposer":"yyyy22","sendAccount":66,"sendChannel":30,"team":"yyyt","templateType":10,"updated":1636978066,"updator":"yyyyu"}
*
* messageTemplate Id 2
* {"auditStatus":10,"auditor":"yyyyyyz","created":1636978066,"creator":"yyyyc","deduplicationTime":1,"expectPushTime":"0","flowId":"yyyy","id":1,"idType":30,"isDeleted":0,"isNightShield":0,"msgContent":"{\"content\":\"{$contentValue}\"}","msgStatus":10,"msgType":20,"name":"test短信","proposer":"yyyy22","sendAccount":66,"sendChannel":30,"team":"yyyt","templateType":10,"updated":1636978066,"updator":"yyyyu"}
*/ */
// 文案参数 @PostMapping("/send")
Map<String, String> variables = new HashMap<>(8); public SendResponse send(@RequestBody SendRequest sendRequest) {
variables.put("contentValue", "6666" + System.currentTimeMillis());
variables.put("title", "yyyyyy");
MessageParam messageParam = new MessageParam().setReceiver(receiver).setVariables(variables);
SendRequest sendRequest = new SendRequest().setCode(BusinessCode.COMMON_SEND.getCode())
.setMessageTemplateId(templateId)
.setMessageParam(messageParam);
return sendService.send(sendRequest); return sendService.send(sendRequest);
} }
} }

@ -7,15 +7,6 @@ ok:
read-timeout: 30 read-timeout: 30
write-timeout: 30 write-timeout: 30
# 腾讯云账号相关的信息配置 TODO
tencent:
sms:
account:
secret-id:
secret-key:
sign_name:
sms-sdk-app-id:
template-id:
# 数据库相关的信息配置 TODO # 数据库相关的信息配置 TODO
spring: spring:
@ -48,7 +39,7 @@ spring:
# 消息topicName TODO # 消息topicName TODO
austin: austin:
topic: topic:
name: austin name: austinTopic
# 监控配置 TODO # 监控配置 TODO
management: management:
@ -75,5 +66,4 @@ apollo:
bootstrap: bootstrap:
enabled: true enabled: true
namespaces: boss.austin namespaces: boss.austin
# tomcat / HikariPool(数据库连接池 配置) TODO # tomcat / HikariPool(数据库连接池 配置) TODO
Loading…
Cancel
Save