Merge branch 'test/stable' into release/3.0
# Conflicts: # src/main/java/com/ai/da/common/RabbitMQ/GenerateConsumer.java # src/main/java/com/ai/da/service/impl/AccountServiceImpl.java
This commit is contained in:
@@ -44,6 +44,10 @@ public class GenerateConsumer {
|
||||
|
||||
@Value("${redis.key.generateResult}")
|
||||
private String generateResultKey;
|
||||
@Value("${redis.key.toProductImageResultKey}")
|
||||
private String toProductImageResultKey;
|
||||
@Value("${redis.key.relightResultKey}")
|
||||
private String relightResultKey;
|
||||
|
||||
public void generate(Message msg, Channel channel, String consumerName) {
|
||||
log.info("============start listening==========");
|
||||
@@ -63,23 +67,14 @@ public class GenerateConsumer {
|
||||
} catch (IOException ex) {
|
||||
log.error("手动确认,不返回队列重新消费");
|
||||
}
|
||||
// 2.2 将该消息从取消列表中删除
|
||||
// redisUtil.removeFromSet(cancelSetKey, uniqueId);
|
||||
} else {
|
||||
// GenerateCollectionVO generateCollectionVO = generateService.generateThroughImageText(generateThroughImageTextDTO);
|
||||
generateService.generateThroughImageText(generateThroughImageTextDTO);
|
||||
// 将消息从redis排队队列中删除,需保证被消费的消息存储到db之后再从redis删除
|
||||
redisUtil.removeFromZSet(consumptionOrderKey, uniqueId);
|
||||
/*if (!Objects.isNull(generateCollectionVO)) {
|
||||
HashMap<String, String> generateResult = new HashMap<>();
|
||||
generateResult.put(uniqueId, JSONObject.toJSONString(generateCollectionVO));
|
||||
// 将结果存在redis中 ,为空时不要存
|
||||
redisUtil.addToMap(resultMapKey, generateResult);
|
||||
}*/
|
||||
|
||||
}
|
||||
} catch (BusinessException e) {
|
||||
log.error(e.getMsg());
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
// channel.basicNack() 为不确认deliveryTag对应的消息,第二个参数是否应用于多消息,第三个参数是否requeue
|
||||
try {
|
||||
// 第二个参数,是否批量确认消息,当传false时,只确认当前 deliveryTag对应的消息;当传true时,会确认当前及之前所有未确认的消息。
|
||||
@@ -94,7 +89,7 @@ public class GenerateConsumer {
|
||||
}
|
||||
// 将入参和错误信息存入数据库
|
||||
String exceptionMessage = JSONObject.toJSONString(generateThroughImageTextDTO) +
|
||||
" Exception message : " + e.getMsg();
|
||||
" Exception message : " + e.getMessage();
|
||||
HashMap<String, String> exceptionInfo = new HashMap<>();
|
||||
exceptionInfo.put(String.valueOf(uniqueId), exceptionMessage);
|
||||
// 存redis
|
||||
@@ -154,63 +149,169 @@ public class GenerateConsumer {
|
||||
|
||||
}
|
||||
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void generateConsumer1(Message msg, Channel channel) {
|
||||
// generate(msg, channel, "consumer 1");
|
||||
// }
|
||||
//
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void generateConsumer2(Message msg, Channel channel) {
|
||||
// generate(msg, channel, "consumer 2");
|
||||
// }
|
||||
//
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void generateConsumer3(Message msg, Channel channel) {
|
||||
// generate(msg, channel, "consumer 3");
|
||||
// }
|
||||
//
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void generateConsumer4(Message msg, Channel channel) {
|
||||
// generate(msg, channel, "consumer 4");
|
||||
// }
|
||||
//
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void generateConsumer5(Message msg, Channel channel) {
|
||||
// generate(msg, channel, "consumer 5");
|
||||
// }
|
||||
//
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void generateConsumer6(Message msg, Channel channel) {
|
||||
// generate(msg, channel, "consumer 6");
|
||||
// }
|
||||
//
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void generateConsumer7(Message msg, Channel channel) {
|
||||
// generate(msg, channel, "consumer 7");
|
||||
// }
|
||||
//
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void generateConsumer8(Message msg, Channel channel) {
|
||||
// generate(msg, channel, "consumer 8");
|
||||
// }
|
||||
//
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void generateConsumer9(Message msg, Channel channel) {
|
||||
// generate(msg, channel, "consumer 9");
|
||||
// }
|
||||
//
|
||||
// @RabbitListener(queues = MQConfig.GENERATE_RESULT_QUEUE)
|
||||
// @RabbitHandler
|
||||
// public void getGenerateResult(Message msg, Channel channel) {
|
||||
// processGenerateResult(msg, channel);
|
||||
// }
|
||||
public void processToProductImageResult(Message msg, Channel channel) {
|
||||
log.info("============processToProductImageResult listening==========");
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
Map<String, String> generateResult = JSONObject.parseObject(msg.getBody(), Map.class);
|
||||
log.info("toProductImage response : {}", generateResult);
|
||||
|
||||
try {
|
||||
log.info("tasks_id : {} start ", generateResult.get("tasks_id"));
|
||||
if (generateResult.get("status").equals("SUCCESS")) {
|
||||
String url = generateResult.get("image_url");
|
||||
String taskId = generateResult.get("tasks_id");
|
||||
String category = generateResult.get("category");
|
||||
generateService.processToProductImageResult(taskId, url, category);
|
||||
} else {
|
||||
// 修改redis中的数据状态为exception
|
||||
String key = toProductImageResultKey + ":" + generateResult.get("tasks_id");
|
||||
redisUtil.addToString(key, new Gson().toJson(new GenerateResultVO(generateResult.get("tasks_id"), null, null, "Fail")), CommonConstant.GENERATE_RESULT_EXPIRE_TIME);
|
||||
// 将异常信息存到exception中
|
||||
HashMap<String, String> exceptionInfo = new HashMap<>();
|
||||
exceptionInfo.put(generateResult.get("tasks_id"), generateResult.get("data"));
|
||||
// 存redis
|
||||
redisUtil.addToMap(exceptionMapKey, exceptionInfo);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
try {
|
||||
channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
|
||||
// 将消息从redis排队队列中删除,需保证被消费的消息存储到db之后再从redis删除
|
||||
redisUtil.removeFromZSet(consumptionOrderKey, generateResult.get("tasks_id"));
|
||||
} catch (IOException exception) {
|
||||
log.error("手动确认,取消返回队列,不再重新消费");
|
||||
}
|
||||
// 将入参和错误信息存入数据库
|
||||
String exceptionMessage = JSONObject.toJSONString(generateResult) +
|
||||
" Exception message : " + e.getMessage();
|
||||
HashMap<String, String> exceptionInfo = new HashMap<>();
|
||||
exceptionInfo.put(String.valueOf(generateResult.get("tasks_id")), exceptionMessage);
|
||||
// 存redis
|
||||
redisUtil.addToMap(exceptionMapKey, exceptionInfo);
|
||||
}
|
||||
|
||||
long end = System.currentTimeMillis();
|
||||
log.info("tasks_id : {}, end , message : {}, 执行时长: {} 毫秒", generateResult.get("tasks_id"), generateResult.get("message"), (end - start));
|
||||
log.info("============ProcessToProductImageResult End listening==========");
|
||||
}
|
||||
|
||||
private void processRelightResult(Message msg, Channel channel) {
|
||||
log.info("============processRelightResult listening==========");
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
Map<String, String> generateResult = JSONObject.parseObject(msg.getBody(), Map.class);
|
||||
log.info("toProductImage response : {}", generateResult);
|
||||
|
||||
try {
|
||||
log.info("tasks_id : {} start ", generateResult.get("tasks_id"));
|
||||
if (generateResult.get("status").equals("SUCCESS")) {
|
||||
String url = generateResult.get("image_url");
|
||||
String taskId = generateResult.get("tasks_id");
|
||||
String category = generateResult.get("category");
|
||||
generateService.processRelightResult(taskId, url, category);
|
||||
} else {
|
||||
// 修改redis中的数据状态为exception
|
||||
String key = relightResultKey + ":" + generateResult.get("tasks_id");
|
||||
redisUtil.addToString(key, new Gson().toJson(new GenerateResultVO(generateResult.get("tasks_id"), null, null, "Fail")), CommonConstant.GENERATE_RESULT_EXPIRE_TIME);
|
||||
// 将异常信息存到exception中
|
||||
HashMap<String, String> exceptionInfo = new HashMap<>();
|
||||
exceptionInfo.put(generateResult.get("tasks_id"), generateResult.get("data"));
|
||||
// 存redis
|
||||
redisUtil.addToMap(exceptionMapKey, exceptionInfo);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
try {
|
||||
channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
|
||||
// 将消息从redis排队队列中删除,需保证被消费的消息存储到db之后再从redis删除
|
||||
redisUtil.removeFromZSet(consumptionOrderKey, generateResult.get("tasks_id"));
|
||||
} catch (IOException exception) {
|
||||
log.error("手动确认,取消返回队列,不再重新消费");
|
||||
}
|
||||
// 将入参和错误信息存入数据库
|
||||
String exceptionMessage = JSONObject.toJSONString(generateResult) +
|
||||
" Exception message : " + e.getMessage();
|
||||
HashMap<String, String> exceptionInfo = new HashMap<>();
|
||||
exceptionInfo.put(String.valueOf(generateResult.get("tasks_id")), exceptionMessage);
|
||||
// 存redis
|
||||
redisUtil.addToMap(exceptionMapKey, exceptionInfo);
|
||||
}
|
||||
|
||||
long end = System.currentTimeMillis();
|
||||
log.info("tasks_id : {}, end , message : {}, 执行时长: {} 毫秒", generateResult.get("tasks_id"), generateResult.get("message"), (end - start));
|
||||
log.info("============ProcessRelightResult End listening==========");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
@RabbitHandler
|
||||
public void generateConsumer1(Message msg, Channel channel) {
|
||||
generate(msg, channel, "consumer 1");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
@RabbitHandler
|
||||
public void generateConsumer2(Message msg, Channel channel) {
|
||||
generate(msg, channel, "consumer 2");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
@RabbitHandler
|
||||
public void generateConsumer3(Message msg, Channel channel) {
|
||||
generate(msg, channel, "consumer 3");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
@RabbitHandler
|
||||
public void generateConsumer4(Message msg, Channel channel) {
|
||||
generate(msg, channel, "consumer 4");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
@RabbitHandler
|
||||
public void generateConsumer5(Message msg, Channel channel) {
|
||||
generate(msg, channel, "consumer 5");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
@RabbitHandler
|
||||
public void generateConsumer6(Message msg, Channel channel) {
|
||||
generate(msg, channel, "consumer 6");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
@RabbitHandler
|
||||
public void generateConsumer7(Message msg, Channel channel) {
|
||||
generate(msg, channel, "consumer 7");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
@RabbitHandler
|
||||
public void generateConsumer8(Message msg, Channel channel) {
|
||||
generate(msg, channel, "consumer 8");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
|
||||
@RabbitHandler
|
||||
public void generateConsumer9(Message msg, Channel channel) {
|
||||
generate(msg, channel, "consumer 9");
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.GENERATE_RESULT_QUEUE)
|
||||
@RabbitHandler
|
||||
public void getGenerateResult(Message msg, Channel channel) {
|
||||
processGenerateResult(msg, channel);
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.TO_PRODUCT_IMAGE_RESULT_QUEUE)
|
||||
@RabbitHandler
|
||||
public void getToProductImageResult(Message msg, Channel channel) {
|
||||
processToProductImageResult(msg, channel);
|
||||
}
|
||||
|
||||
@RabbitListener(queues = MQConfig.RELIGHT_RESULT_QUEUE)
|
||||
@RabbitHandler
|
||||
public void getRelightResult(Message msg, Channel channel) {
|
||||
processRelightResult(msg, channel);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,16 +13,22 @@ public class MQConfig {
|
||||
// ==================================================================
|
||||
// public static final String GENERATE_QUEUE = "generate-queue-local";
|
||||
public static final String GENERATE_QUEUE = "generate-queue-prod";
|
||||
|
||||
// public static final String GENERATE_QUEUE = "generate-queue-prod";
|
||||
//
|
||||
// public static final String SR_QUEUE = "SR-queue-local";
|
||||
public static final String SR_QUEUE = "SR-queue-prod";
|
||||
|
||||
public static final String SR_QUEUE = "SR-queue-prod";
|
||||
// public static final String SR_QUEUE = "SR-queue-prod";
|
||||
//
|
||||
// public static final String SR_RESULT_QUEUE = "SuperResolution-local";
|
||||
public static final String SR_RESULT_QUEUE = "SuperResolution-prod";
|
||||
|
||||
public static final String SR_RESULT_QUEUE = "SuperResolution-prod";
|
||||
// public static final String SR_RESULT_QUEUE = "SuperResolution-prod";
|
||||
//
|
||||
// public static final String GENERATE_RESULT_QUEUE = "GenerateImage-local";
|
||||
public static final String GENERATE_RESULT_QUEUE = "GenerateImage-prod";
|
||||
|
||||
public static final String TO_PRODUCT_IMAGE_RESULT_QUEUE = "ToProductImage-prod";
|
||||
|
||||
public static final String RELIGHT_RESULT_QUEUE = "Relight-prod";
|
||||
public MQConfig() {
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package com.ai.da.common.config;
|
||||
|
||||
import com.ai.da.common.utils.ExcelReader;
|
||||
import com.ai.da.common.utils.MinioUtil;
|
||||
import com.ai.da.common.utils.SendEmailUtil;
|
||||
import com.ai.da.mapper.primary.AccountMapper;
|
||||
import com.ai.da.mapper.primary.TrialOrderMapper;
|
||||
import com.ai.da.mapper.primary.entity.Account;
|
||||
import com.ai.da.mapper.primary.entity.TrialOrder;
|
||||
import com.ai.da.mapper.primary.*;
|
||||
import com.ai.da.mapper.primary.entity.*;
|
||||
import com.ai.da.mapper.secondary.AttributeRetrievalMapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
@@ -17,15 +19,28 @@ import javax.annotation.PostConstruct;
|
||||
import javax.annotation.Resource;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class MyTaskScheduler {
|
||||
|
||||
@PostConstruct
|
||||
public void test() {
|
||||
// clearMinio();
|
||||
// addSystemFileStyle();
|
||||
}
|
||||
|
||||
@Resource
|
||||
private AccountMapper accountMapper;
|
||||
|
||||
@@ -34,7 +49,7 @@ public class MyTaskScheduler {
|
||||
|
||||
// 定时任务,每十五天执行一次
|
||||
// @Scheduled(cron = "0 0 0 ? * MON")
|
||||
@Scheduled(cron = "0 0 0 */15 * ?")
|
||||
// @Scheduled(cron = "0 0 0 */15 * ?")
|
||||
public void checkExpiry() {
|
||||
// 检测正式用户是否快要过期
|
||||
QueryWrapper<Account> qw = new QueryWrapper<>();
|
||||
@@ -68,10 +83,10 @@ public class MyTaskScheduler {
|
||||
}
|
||||
}
|
||||
}
|
||||
@Scheduled(cron = "0 0 8 * * ?")
|
||||
// @Scheduled(cron = "0 0 8 * * ?")
|
||||
public void sendTrialOrderExcelToManagements() {
|
||||
// 获取前一天日期
|
||||
LocalDate yesterday = LocalDate.now().minusDays(1);
|
||||
LocalDate yesterday = LocalDate.now().minusDays(3);
|
||||
|
||||
// 查询前一天的试用订单
|
||||
QueryWrapper<TrialOrder> qw = new QueryWrapper<>();
|
||||
@@ -134,4 +149,174 @@ public class MyTaskScheduler {
|
||||
SendEmailUtil.sendNoExcelEmail("kimwong@code-create.com.hk", null);
|
||||
}
|
||||
}
|
||||
|
||||
@Resource
|
||||
private UserLikeGroupMapper userLikeGroupMapper;
|
||||
@Resource
|
||||
private UserLikeMapper userLikeMapper;
|
||||
@Resource
|
||||
private TDesignPythonOutfitMapper designPythonOutfitMapper;
|
||||
@Resource
|
||||
private TDesignPythonOutfitDetailMapper designPythonOutfitDetailMapper;
|
||||
@Resource
|
||||
private DesignItemMapper designItemMapper;
|
||||
@Resource
|
||||
private DesignItemDetailMapper designItemDetailMapper;
|
||||
@Resource
|
||||
private MinioUtil minioUtil;
|
||||
public void clearMinio() {
|
||||
// 获取当前所有history
|
||||
QueryWrapper<UserLikeGroup> userLikeGroupQueryWrapper = new QueryWrapper<>();
|
||||
List<UserLikeGroup> userLikeGroupList = userLikeGroupMapper.selectList(userLikeGroupQueryWrapper);
|
||||
List<Long> userLikeGroupIdList = userLikeGroupList.stream().map(UserLikeGroup::getId).collect(Collectors.toList());
|
||||
QueryWrapper<UserLike> userLikeQueryWrapper = new QueryWrapper<>();
|
||||
userLikeQueryWrapper.lambda().in(UserLike::getUserLikeGroupId, userLikeGroupIdList);
|
||||
// 所有喜欢的图片
|
||||
List<UserLike> userLikes = userLikeMapper.selectList(userLikeQueryWrapper);
|
||||
List<Long> designOutfitIdList = userLikes.stream().map(UserLike::getDesignOutfitId).collect(Collectors.toList());
|
||||
QueryWrapper<TDesignPythonOutfit> designPythonOutfitQueryWrapper = new QueryWrapper<>();
|
||||
designPythonOutfitQueryWrapper.lambda().notIn(TDesignPythonOutfit::getId, designOutfitIdList);
|
||||
List<TDesignPythonOutfit> tDesignPythonOutfits = designPythonOutfitMapper.selectList(designPythonOutfitQueryWrapper);
|
||||
// int i = 0;
|
||||
// for (TDesignPythonOutfit tDesignPythonOutfit : tDesignPythonOutfits) {
|
||||
// String designUrl = tDesignPythonOutfit.getDesignUrl();
|
||||
// if (StringUtils.isNotBlank(designUrl)) {
|
||||
// minioUtil.deleteObject(designUrl);
|
||||
// i ++;
|
||||
// }
|
||||
// QueryWrapper<TDesignPythonOutfitDetail> designPythonOutfitDetailQueryWrapper = new QueryWrapper<>();
|
||||
// designPythonOutfitDetailQueryWrapper.lambda().eq(TDesignPythonOutfitDetail::getDesignPythonOutfitId, tDesignPythonOutfit.getId());
|
||||
// List<TDesignPythonOutfitDetail> tDesignPythonOutfitDetails = designPythonOutfitDetailMapper.selectList(designPythonOutfitDetailQueryWrapper);
|
||||
// for (TDesignPythonOutfitDetail tDesignPythonOutfitDetail : tDesignPythonOutfitDetails) {
|
||||
// if (!tDesignPythonOutfitDetail.getImageCategory().equals("body")) {
|
||||
// if (StringUtils.isNotBlank(tDesignPythonOutfitDetail.getImageUrl())) {
|
||||
// minioUtil.deleteObject(tDesignPythonOutfitDetail.getImageUrl());
|
||||
// i ++;
|
||||
// }
|
||||
// if (StringUtils.isNotBlank(tDesignPythonOutfitDetail.getMaskUrl())) {
|
||||
// minioUtil.deleteObject(tDesignPythonOutfitDetail.getMaskUrl());
|
||||
// i ++;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
System.out.println("i");
|
||||
// List<Long> designItemIdList = userLikes.stream().map(UserLike::getDesignItemId).collect(Collectors.toList());
|
||||
// QueryWrapper<DesignItem> designItemQueryWrapper = new QueryWrapper<>();
|
||||
// designItemQueryWrapper.lambda().in(DesignItem::getId,designItemIdList);
|
||||
// List<DesignItem> designItems = designItemMapper.selectList(designItemQueryWrapper);
|
||||
// for (DesignItem designItem : designItems) {
|
||||
// QueryWrapper<DesignItemDetail> designItemDetailQueryWrapper = new QueryWrapper<>();
|
||||
// designItemDetailQueryWrapper.lambda().eq(DesignItemDetail::getDesignItemId, designItem.getId());
|
||||
// List<DesignItemDetail> designItemDetails = designItemDetailMapper.selectList(designItemDetailQueryWrapper);
|
||||
// for (DesignItemDetail designItemDetail : designItemDetails) {
|
||||
//
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
@Resource
|
||||
private AttributeRetrievalMapper attributeRetrievalMapper;
|
||||
|
||||
public void addSystemFileStyle() {
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(5);
|
||||
|
||||
try {
|
||||
String[] filePaths = {
|
||||
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Blouse style output updated25.6.2024.xlsx",
|
||||
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Dress style output updated25.6.2024.xlsx",
|
||||
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Outerwear style output.xlsx",
|
||||
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Skirt style output .xlsx",
|
||||
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Trousers style output.xlsx"
|
||||
};
|
||||
|
||||
for (String filePath : filePaths) {
|
||||
executorService.submit(() -> processExcelFile(filePath));
|
||||
}
|
||||
} finally {
|
||||
executorService.shutdown();
|
||||
try {
|
||||
if (!executorService.awaitTermination(60, TimeUnit.MINUTES)) {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processExcelFile(String filePath) {
|
||||
System.out.println("线程开始");
|
||||
try {
|
||||
List<List<String>> excelData = ExcelReader.readExcel(filePath);
|
||||
String tableName = getTableNameFromFilePath(filePath);
|
||||
String prefix = getPrefixFromFilePath(filePath);
|
||||
|
||||
for (List<String> columnData : excelData) {
|
||||
String style = columnData.get(0);
|
||||
for (int i = 1; i < columnData.size(); i++) {
|
||||
String fileName = columnData.get(i);
|
||||
if (StringUtils.isBlank(fileName)) {
|
||||
continue;
|
||||
}
|
||||
if ("X".equals(style)) {
|
||||
attributeRetrievalMapper.updateStyleByFileName("X", prefix + fileName, tableName);
|
||||
System.out.println(fileName);
|
||||
} else {
|
||||
attributeRetrievalMapper.updateStyleByFileName(style, prefix + fileName, tableName);
|
||||
System.out.println(fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private String getTableNameFromFilePath(String filePath) {
|
||||
if (filePath.contains("Blouse")) {
|
||||
return "female_top";
|
||||
} else if (filePath.contains("Dress")) {
|
||||
return "female_dress";
|
||||
} else if (filePath.contains("Outerwear")) {
|
||||
return "female_outwear";
|
||||
} else if (filePath.contains("Skirt")) {
|
||||
return "female_skirt";
|
||||
} else if (filePath.contains("Trousers")) {
|
||||
return "female_pants";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private String getPrefixFromFilePath(String filePath) {
|
||||
if (filePath.contains("Blouse")) {
|
||||
return "blouse/";
|
||||
} else if (filePath.contains("Dress")) {
|
||||
return "dress/";
|
||||
} else if (filePath.contains("Outerwear")) {
|
||||
return "outwear/";
|
||||
} else if (filePath.contains("Skirt")) {
|
||||
return "skirt/";
|
||||
} else if (filePath.contains("Trousers")) {
|
||||
return "trousers/";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// public static List<String> getFileNames(String directoryPath) {
|
||||
// List<String> fileNames = new ArrayList<>();
|
||||
// Path path = Paths.get(directoryPath);
|
||||
//
|
||||
// try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
|
||||
// for (Path entry : stream) {
|
||||
// if (Files.isRegularFile(entry)) {
|
||||
// fileNames.add(entry.getFileName().toString());
|
||||
// }
|
||||
// }
|
||||
// } catch (IOException e) {
|
||||
// System.err.println("Error reading directory: " + e.getMessage());
|
||||
// }
|
||||
//
|
||||
// return fileNames;
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -11,4 +11,26 @@ public class CommonConstant {
|
||||
// 单位 秒 一天过期 in redis
|
||||
public static final Long GENERATE_RESULT_EXPIRE_TIME = 24 * 60 * 60L;
|
||||
|
||||
public static class Numbers{
|
||||
public static final Integer NUMBER_10 = 10;
|
||||
public static final Integer NUMBER_1000 = 1000;
|
||||
public static final Integer NUMBER_10080 = 10080;
|
||||
}
|
||||
|
||||
public static final String GENERATE_PATH = "/api/generate_image";
|
||||
|
||||
public static final String GENERATE_SINGLE_LOGO = "/api/generate_single_logo";
|
||||
|
||||
public static final String GENERATE_SLOGAN = "/api/slogan";
|
||||
|
||||
public static final String GENERATE_CANCEL = "/api/generate_cancel/";
|
||||
|
||||
public static final String GENERATE_LOGO_SINGLE_CANCEL = "/api/generate_single_logo_cancel/";
|
||||
|
||||
public static final String PYTHON_PORT_9996 = "9996";
|
||||
|
||||
public static final String PYTHON_PORT_9997 = "9997";
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.ai.da.common.enums;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
@@ -36,7 +38,18 @@ public enum CollectionLevel2TypeEnum {
|
||||
* 男装下装
|
||||
*/
|
||||
BOTTOMS("Bottoms"),
|
||||
;
|
||||
/**
|
||||
* 印花-logo
|
||||
*/
|
||||
LOGO("Logo"),
|
||||
/**
|
||||
* 印花-slogan
|
||||
*/
|
||||
SLOGAN("Slogan"),
|
||||
/**
|
||||
* 印花-图案
|
||||
*/
|
||||
Pattern("Pattern");
|
||||
|
||||
private String realName;
|
||||
|
||||
@@ -51,4 +64,8 @@ public enum CollectionLevel2TypeEnum {
|
||||
public static CollectionLevel2TypeEnum of(String realName) {
|
||||
return Stream.of(CollectionLevel2TypeEnum.values()).filter(v -> v.getRealName().equals(realName)).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
public static List<String> printType() {
|
||||
return Arrays.asList(LOGO.getRealName(), SLOGAN.getRealName(), Pattern.getRealName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,19 +8,29 @@ import lombok.Getter;
|
||||
public enum CreditsEventsEnum {
|
||||
|
||||
PRICE("price","6"),
|
||||
// PRICE("price","0.1"),
|
||||
|
||||
BUY_CREDITS("Buy Credits","600"),
|
||||
BUY_CREDITS("Buy Credits","60"),
|
||||
// BUY_CREDITS("Buy Credits","10"),
|
||||
|
||||
INIT("init", "500"),
|
||||
// 每月更新
|
||||
INIT_YEARLY("init_yearly", "6000"),
|
||||
INIT_MONTHLY("init_monthly", "5000"),
|
||||
INIT_TRIAL("init_trial", "100"),
|
||||
INIT_WEEKLY("init_weekly","6000"),
|
||||
|
||||
DAILY_CHECKIN("Daily Check-In", "20"),
|
||||
// SUPER_RESOLUTION("Super Resolution","30"),
|
||||
SUPER_RESOLUTION("Super Resolution","10"),
|
||||
SLOGAN("Slogan","10"),
|
||||
LOGO("Logo","5"),
|
||||
PATTERN("Pattern","5"),
|
||||
MOOD_BOARD("MoodBoard","5"),
|
||||
SKETCH_BOARD("SketchBoard","5"),
|
||||
TO_PRODUCT_IMAGE("ToProductImage","5"),
|
||||
RELIGHT("Relight","5"),
|
||||
QUESTIONNAIRE("Questionnaire","100"),
|
||||
|
||||
SOCIAL_MEDIA_SHARING("Social Media Sharing","20"),
|
||||
|
||||
// SUPER_RESOLUTION("Super Resolution","300"),
|
||||
SUPER_RESOLUTION("Super Resolution","5"),
|
||||
|
||||
OTHER("Other","10");
|
||||
OTHER("Other","5");
|
||||
|
||||
private String name;
|
||||
|
||||
|
||||
@@ -48,8 +48,9 @@ public class AuthenticationFilter extends OncePerRequestFilter {
|
||||
"/api/third/party/addUser","/api/third/party/addTrialUser", "/api/third/party/editUser", "/api/element/initDefaultSysFile",
|
||||
"/api/third/party/addNoLoginRequiredNew","/api/third/party/deleteNoLoginRequiredNew",
|
||||
"/api/third/party/existNoLoginRequired","/api/third/party/getRedirectUrl",
|
||||
// "/api/python/chatStream",
|
||||
"/api/python/flush","/api/account/healthy","/api/ali-pay/trade/notify","/api/paypal/ipn/back","/api/alipay-hk/trade/notify"
|
||||
"/api/python/flush","/api/account/healthy","/api/ali-pay/trade/notify","/api/paypal/ipn/back","/api/alipay-hk/trade/notify",
|
||||
"/api/portfolio/page", "/api/portfolio/detail", "/api/portfolio/commentPage", "/api/portfolio/viewsIncrease",
|
||||
"/api/account/designWorksRegister","/api/account/questionnaire"
|
||||
);
|
||||
|
||||
@Override
|
||||
|
||||
31
src/main/java/com/ai/da/common/task/AccountTask.java
Normal file
31
src/main/java/com/ai/da/common/task/AccountTask.java
Normal file
@@ -0,0 +1,31 @@
|
||||
package com.ai.da.common.task;
|
||||
|
||||
import com.ai.da.service.AccountService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class AccountTask {
|
||||
|
||||
@Resource
|
||||
private AccountService accountService;
|
||||
|
||||
/** 每周日晚上刷新 年付用户、月付用户的积分 */
|
||||
@Scheduled(cron = "59 59 23 ? * SUN")
|
||||
// @Scheduled(cron = "59 59 23 * * ?")
|
||||
public void refreshCreditsMonthly(){
|
||||
log.info("每周日晚11:59:59刷新付费用户积分为 6000");
|
||||
accountService.refreshCreditsWeekly();
|
||||
}
|
||||
|
||||
// todo 多久执行一次?
|
||||
@Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes
|
||||
public void getPaidUser(){
|
||||
// 获取code-create 表中 指定日期之后 订单状态为wc-processing的订单
|
||||
accountService.extendValidityForCC();
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ public class PaypalTask {
|
||||
@Resource
|
||||
private PayPalCheckoutService payPalCheckoutService;
|
||||
|
||||
@Scheduled(cron = "0/30 * * * * ?")
|
||||
// @Scheduled(cron = "0/30 * * * * ?")
|
||||
public void orderConfirm() throws SerializeException {
|
||||
|
||||
log.info("PayPal orderConfirm 被执行......");
|
||||
|
||||
@@ -50,6 +50,9 @@ public class AlipayHKEncryptionUtil {
|
||||
@Value("${alipayHK.rsaPublicKey}")
|
||||
private String publicKeyPath;
|
||||
|
||||
@Value("${alipayHK.CODPublicKey}")
|
||||
private String CODPublicKeyPath;
|
||||
|
||||
|
||||
/**
|
||||
* 加密
|
||||
@@ -70,7 +73,8 @@ public class AlipayHKEncryptionUtil {
|
||||
// The path to the rsa private key file, DO NOT save this key to a publicly accessible location
|
||||
// 使用私钥创建数字签名
|
||||
// Mode, aes-128-cbc for 128bit key
|
||||
String mode = "aes-128-cbc";
|
||||
// String mode = "aes-128-cbc";
|
||||
String mode = "aes-256-cbc";
|
||||
// Padding mode
|
||||
String padding = "pkcs7";
|
||||
// signature alogrithm
|
||||
@@ -84,18 +88,11 @@ public class AlipayHKEncryptionUtil {
|
||||
requestMessage.setRequest_uuid(UUID.randomUUID().toString());
|
||||
// HashMap<String, Object> param = new HashMap<>();
|
||||
requestMessage.setParameters(param);
|
||||
/*String orderRef = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
|
||||
param.put("order_ref", orderRef);
|
||||
param.put("amount", 208.12);
|
||||
param.put("subject", "四月帳單 April Bill");
|
||||
param.put("wallet", "ALIPAYHK");
|
||||
param.put("segment_id", segmentId);
|
||||
param.put("payment_solution", "WAP");*/
|
||||
|
||||
|
||||
// Serialize message body
|
||||
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
|
||||
String content = gson.toJson(requestMessage);
|
||||
log.info("alipay-hk request 加密前:{}", content);
|
||||
|
||||
// Secure random iv 获取随机种子
|
||||
SecureRandom secureRandom = new SecureRandom();
|
||||
@@ -153,7 +150,7 @@ public class AlipayHKEncryptionUtil {
|
||||
|
||||
// Encode to json
|
||||
String jsonEncoded = JSONObject.toJSONString(alipayHKRequestDTO);
|
||||
log.info(jsonEncoded);
|
||||
log.info("alipay-hk request 加密加签后:{}",jsonEncoded);
|
||||
|
||||
// String info = AlipayHKRequestUtil.createOrder(alipayHKRequestDTO);
|
||||
// log.info(info);
|
||||
@@ -341,18 +338,25 @@ public class AlipayHKEncryptionUtil {
|
||||
Base64.Decoder decoder = Base64.getDecoder();
|
||||
// Verify key
|
||||
try {
|
||||
// PublicKey publicKey = readPublicKey(new File(publicKeyPath));
|
||||
InputStreamReader isrPub = new InputStreamReader(new FileInputStream(publicKeyPath));
|
||||
// 从指定的路径读取公钥文件
|
||||
InputStreamReader isrPub = new InputStreamReader(new FileInputStream(CODPublicKeyPath));
|
||||
PEMParser pemParserPub = new PEMParser(isrPub);
|
||||
// 使用 PEMParser 解析公钥文件
|
||||
SubjectPublicKeyInfo pubInfo = (SubjectPublicKeyInfo) pemParserPub.readObject();
|
||||
// 从 SubjectPublicKeyInfo 创建 AsymmetricKeyParameter 对象
|
||||
AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(pubInfo);
|
||||
// Verifying
|
||||
// Verifying; 创建 RSADigestSigner 对象并使用 SHA-256 作为摘要算法
|
||||
RSADigestSigner verifier = new RSADigestSigner(new SHA256Digest());
|
||||
// 初始化 RSADigestSigner,设置为验证模式并提供公钥参数
|
||||
verifier.init(false, pubKey);
|
||||
byte[] signMessageForVerifing = data.getBytes();
|
||||
byte[] signatureBase64ForVerifing = decoder.decode(signatureBase64);
|
||||
verifier.update(signMessageForVerifing, 0, signMessageForVerifing.length);
|
||||
Boolean verifyResult = verifier.verifySignature(signatureBase64ForVerifing);
|
||||
// 将要验证的数据转换为字节数组
|
||||
byte[] signMessageForVerifying = data.getBytes();
|
||||
// 将 Base64 编码的签名转换为字节数组
|
||||
byte[] signatureBase64ForVerifying = decoder.decode(signatureBase64);
|
||||
// 使用签名器更新要验证的数据
|
||||
verifier.update(signMessageForVerifying, 0, signMessageForVerifying.length);
|
||||
// 验证签名并返回结果
|
||||
Boolean verifyResult = verifier.verifySignature(signatureBase64ForVerifying);
|
||||
return verifyResult;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
|
||||
@@ -17,7 +17,7 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public class AlipayHKRequestUtil {
|
||||
|
||||
public String createOrder(AlipayHKRequestDTO alipayHKRequestDTO) throws IOException {
|
||||
public String requestAlipayHK(AlipayHKRequestDTO alipayHKRequestDTO) {
|
||||
OkHttpClient client = new OkHttpClient().newBuilder()
|
||||
.connectTimeout(30, TimeUnit.SECONDS)
|
||||
.pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
|
||||
@@ -29,7 +29,7 @@ public class AlipayHKRequestUtil {
|
||||
log.info("Alipay-HK send request unix timestamp: {}", epochMilli);
|
||||
|
||||
String jsonString = JSONObject.toJSONString(alipayHKRequestDTO, SerializerFeature.WriteMapNullValue);
|
||||
log.info(jsonString);
|
||||
// log.info(jsonString);
|
||||
|
||||
RequestBody body = RequestBody.create(mediaType, jsonString);
|
||||
|
||||
|
||||
33
src/main/java/com/ai/da/common/utils/ExcelReader.java
Normal file
33
src/main/java/com/ai/da/common/utils/ExcelReader.java
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.ai.da.common.utils;
|
||||
|
||||
import lombok.Data;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class ExcelReader {
|
||||
public static List<List<String>> readExcel(String filePath) throws IOException {
|
||||
List<List<String>> data = new ArrayList<>();
|
||||
try (FileInputStream fis = new FileInputStream(filePath);
|
||||
Workbook workbook = new XSSFWorkbook(fis)) {
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
int numberOfColumns = sheet.getRow(0).getLastCellNum();
|
||||
|
||||
for (int i = 0; i < numberOfColumns; i++) {
|
||||
List<String> columnData = new ArrayList<>();
|
||||
for (Row row : sheet) {
|
||||
columnData.add(row.getCell(i).getStringCellValue());
|
||||
}
|
||||
data.add(columnData);
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import io.minio.http.Method;
|
||||
import io.minio.messages.DeleteError;
|
||||
import io.minio.messages.DeleteObject;
|
||||
import io.minio.messages.Item;
|
||||
import io.netty.util.internal.StringUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
@@ -26,6 +28,7 @@ import java.util.stream.Collectors;
|
||||
* @description: minio工具类
|
||||
* @version:3.0
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MinioUtil {
|
||||
@Autowired
|
||||
@@ -370,7 +373,7 @@ public class MinioUtil {
|
||||
* @param expiry 过期时间(单位:分)
|
||||
* @return 文件的临时URL,如果出现异常则返回null
|
||||
*/
|
||||
public String getPresignedUrl(String bucketName, String fileName, int expiry) {
|
||||
public String getPreSignedUrl(String bucketName, String fileName, int expiry) {
|
||||
try {
|
||||
return minioClient.getPresignedObjectUrl(
|
||||
GetPresignedObjectUrlArgs.builder()
|
||||
@@ -386,7 +389,7 @@ public class MinioUtil {
|
||||
}
|
||||
}
|
||||
|
||||
public String getPresignedUrl(String path, int expiry) {
|
||||
public String getPreSignedUrl(String path, int expiry) {
|
||||
if (LocalCacheUtils.getPresignedUrlCache(path) != null) {
|
||||
return LocalCacheUtils.getPresignedUrlCache(path);
|
||||
} else {
|
||||
@@ -396,12 +399,28 @@ public class MinioUtil {
|
||||
int index = path.indexOf("/");
|
||||
String bucketName = path.substring(0, index);
|
||||
String fileName = path.substring(index + 1);
|
||||
String presignedUrl = getPresignedUrl(bucketName, fileName, expiry);
|
||||
String presignedUrl = getPreSignedUrl(bucketName, fileName, expiry);
|
||||
LocalCacheUtils.setPresignedUrlCache(path, presignedUrl);
|
||||
return presignedUrl;
|
||||
}
|
||||
}
|
||||
|
||||
public String getPreSignedUrl(String path, int expiry, boolean resetCache) {
|
||||
if (resetCache || LocalCacheUtils.getPresignedUrlCache(path) == null) {
|
||||
if (!path.contains("/")) {
|
||||
throw new BusinessException("The path is error!");
|
||||
}
|
||||
int index = path.indexOf("/");
|
||||
String bucketName = path.substring(0, index);
|
||||
String fileName = path.substring(index + 1);
|
||||
String presignedUrl = getPreSignedUrl(bucketName, fileName, expiry);
|
||||
LocalCacheUtils.setPresignedUrlCache(path, presignedUrl);
|
||||
return presignedUrl;
|
||||
} else {
|
||||
return LocalCacheUtils.getPresignedUrlCache(path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将桶名、文件名从url中分离出来
|
||||
*
|
||||
@@ -419,7 +438,7 @@ public class MinioUtil {
|
||||
fileName.append("/");
|
||||
}
|
||||
}
|
||||
return getPresignedUrl(bucketName, String.valueOf(fileName), expiry);
|
||||
return getPreSignedUrl(bucketName, String.valueOf(fileName), expiry);
|
||||
}
|
||||
|
||||
public boolean doesObjectExist(String bucketName, String objectName) {
|
||||
@@ -437,11 +456,33 @@ public class MinioUtil {
|
||||
}
|
||||
}
|
||||
|
||||
public String base64Upload(String base64, String bucketName){
|
||||
public String base64UploadToPath(String base64, String bucketName, String path){
|
||||
String[] parts = base64.split(",");
|
||||
String imageType = parts[0].split("/")[1].split(";")[0];
|
||||
String base64Data = parts[1];
|
||||
return uploadImageFromBase64(bucketName, base64Data, imageType);
|
||||
|
||||
byte[] imageBytes = Base64.getDecoder().decode(base64Data);
|
||||
String fileName;
|
||||
if (!StringUtil.isNullOrEmpty(path)){
|
||||
fileName = path + "." + imageType; // or any other image format
|
||||
}else {
|
||||
fileName = UUID.randomUUID() + "." + imageType;
|
||||
}
|
||||
|
||||
try (InputStream in = new ByteArrayInputStream(imageBytes)) {
|
||||
minioClient.putObject(PutObjectArgs.builder()
|
||||
.bucket(bucketName)
|
||||
.object(fileName)
|
||||
.stream(in, in.available(), -1)
|
||||
.contentType("image/" + imageType) // Set the content type according to your image format
|
||||
.build()
|
||||
);
|
||||
|
||||
return bucketName + "/" + fileName;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
return null; // or throw an exception
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,10 +7,12 @@ import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -164,4 +166,54 @@ public class RedisUtil {
|
||||
redisTemplate.delete(key);
|
||||
}
|
||||
|
||||
public final static String PORTFOLIO_LIKE_KEY = "portfolio:like:";
|
||||
|
||||
public void likePost(Long portfolioId, Long userId) {
|
||||
redisTemplate.opsForSet().add(PORTFOLIO_LIKE_KEY + portfolioId, String.valueOf(userId));
|
||||
}
|
||||
|
||||
public Long getLikeCount(Long portfolioId) {
|
||||
String key = PORTFOLIO_LIKE_KEY + portfolioId;
|
||||
return redisTemplate.opsForSet().size(key);
|
||||
}
|
||||
|
||||
public List<Long> getLikedPortfolios(Long userId) {
|
||||
// 获取所有包含PORTFOLIO_LIKE_KEY的键
|
||||
Set<String> likedPortfolios = redisTemplate.keys(PORTFOLIO_LIKE_KEY + "*");
|
||||
|
||||
// 如果没有喜欢的,返回空列表
|
||||
if (likedPortfolios == null || likedPortfolios.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
// 过滤出包含指定用户ID的键,并提取投资组合ID
|
||||
return likedPortfolios.stream()
|
||||
.filter(key -> redisTemplate.opsForSet().isMember(key, String.valueOf(userId)))
|
||||
.map(key -> Long.valueOf(key.replace(PORTFOLIO_LIKE_KEY, "")))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void unLikePost(Long portfolioId, Long userId) {
|
||||
redisTemplate.opsForSet().remove(PORTFOLIO_LIKE_KEY + portfolioId, userId.toString());
|
||||
}
|
||||
|
||||
// 检查用户是否喜欢某个作品
|
||||
public boolean isPostLikedByUser(Long portfolioId, Long userId) {
|
||||
String key = PORTFOLIO_LIKE_KEY + portfolioId;
|
||||
Boolean isMember = redisTemplate.opsForSet().isMember(key, userId.toString());
|
||||
return isMember != null && isMember;
|
||||
}
|
||||
|
||||
public final static String PORTFOLIO_VIEW_KEY = "portfolio:view:";
|
||||
|
||||
public void increaseViewCount(Long portfolioId) {
|
||||
String key = PORTFOLIO_VIEW_KEY + portfolioId;
|
||||
redisTemplate.opsForValue().increment(key);
|
||||
}
|
||||
|
||||
public Long getViewCount(Long portfolioId) {
|
||||
String key = PORTFOLIO_VIEW_KEY + portfolioId;
|
||||
return redisTemplate.opsForValue().increment(key, 0);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
364
src/main/java/com/ai/da/common/utils/S3Util.java
Normal file
364
src/main/java/com/ai/da/common/utils/S3Util.java
Normal file
@@ -0,0 +1,364 @@
|
||||
package com.ai.da.common.utils;
|
||||
|
||||
import com.ai.da.common.config.exception.BusinessException;
|
||||
import com.ai.da.common.constant.CommonConstant;
|
||||
import io.netty.util.internal.StringUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.core.ResponseBytes;
|
||||
import software.amazon.awssdk.core.sync.RequestBody;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.S3Configuration;
|
||||
import software.amazon.awssdk.services.s3.model.*;
|
||||
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
|
||||
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
|
||||
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.*;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class S3Util {
|
||||
|
||||
@Value("${aws.s3.accessKeyId}")
|
||||
private String accessKeyId;
|
||||
|
||||
@Value("${aws.s3.secretKey}")
|
||||
private String secretKey;
|
||||
|
||||
@Value("${aws.s3.regionName}")
|
||||
private String region;
|
||||
|
||||
public static String S3_ACCESS_KEY_ID = null;
|
||||
|
||||
public static String S3_SECRET_KEY = null;
|
||||
|
||||
public static String S3_REGION = null;
|
||||
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
S3_ACCESS_KEY_ID = accessKeyId;
|
||||
S3_SECRET_KEY = secretKey;
|
||||
S3_REGION = region;
|
||||
}
|
||||
|
||||
private static S3Client s3Client;
|
||||
|
||||
private static S3Presigner s3Presigner;
|
||||
|
||||
/**
|
||||
* @return software.amazon.awssdk.services.s3.S3Client
|
||||
* @description: 获取S3客户端对象
|
||||
*/
|
||||
public synchronized S3Client getS3Client() {
|
||||
if (null == s3Client) {
|
||||
s3Client = S3Client.builder()
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(S3_ACCESS_KEY_ID, S3_SECRET_KEY)))
|
||||
// .endpointOverride(URI.create(S3_URI))
|
||||
.serviceConfiguration(item -> item.pathStyleAccessEnabled(true).checksumValidationEnabled(false))
|
||||
.region(Region.of(S3_REGION))
|
||||
.build();
|
||||
}
|
||||
|
||||
return s3Client;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return software.amazon.awssdk.services.s3.presigner.S3Presigner
|
||||
* @description: 获取预签名对象
|
||||
*/
|
||||
public synchronized S3Presigner getS3PreSigner() {
|
||||
if (null == s3Presigner) {
|
||||
s3Presigner = S3Presigner.builder()
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(S3_ACCESS_KEY_ID, S3_SECRET_KEY)))
|
||||
// .endpointOverride(URI.create(S3_URI))
|
||||
.serviceConfiguration(S3Configuration.builder()
|
||||
.checksumValidationEnabled(false)
|
||||
.pathStyleAccessEnabled(true)
|
||||
.build())
|
||||
.region(Region.of(S3_REGION))
|
||||
.build();
|
||||
}
|
||||
return s3Presigner;
|
||||
}
|
||||
|
||||
public String uploadImageFromBase64(String bucketName, String base64Image, String imageType) {
|
||||
S3Client s3Client = getS3Client();
|
||||
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
|
||||
String fileName = UUID.randomUUID() + "." + imageType; // or any other image format
|
||||
|
||||
try (InputStream in = new ByteArrayInputStream(imageBytes)) {
|
||||
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.contentType("image/png")
|
||||
.contentLength((long) in.available())
|
||||
.key(fileName)
|
||||
.acl(ObjectCannedACL.PUBLIC_READ)
|
||||
.build();
|
||||
s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(in, in.available()));
|
||||
|
||||
log.info("uploadImageFromBase64 上传的位置:桶 - {},路径 - {}", bucketName, fileName);
|
||||
return bucketName + "/" + fileName;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null; // or throw an exception
|
||||
}
|
||||
}
|
||||
|
||||
public String upload(String bucketName, String path, MultipartFile file) {
|
||||
S3Client s3Client = getS3Client();
|
||||
try {
|
||||
String fileName = file.getOriginalFilename();
|
||||
assert fileName != null;
|
||||
String[] split = fileName.split("\\.");
|
||||
if (split.length > 1) {
|
||||
fileName = path + "/" + UUID.randomUUID() + "." + split[split.length - 1];
|
||||
} else {
|
||||
fileName = path + "/" + UUID.randomUUID();
|
||||
}
|
||||
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.contentType(file.getContentType())
|
||||
.contentLength(file.getSize())
|
||||
.key(fileName)
|
||||
.acl(ObjectCannedACL.PUBLIC_READ)
|
||||
.build();
|
||||
s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
|
||||
|
||||
log.info("upload 上传的位置:桶 - {},路径 - {}", bucketName, fileName);
|
||||
return bucketName + "/" + fileName;
|
||||
} catch (Exception e) {
|
||||
log.error("上传文件到S3失败 异常:{}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// todo
|
||||
public String upload(String bucketName, String path, MultipartFile file, String copy) {
|
||||
S3Client s3Client = getS3Client();
|
||||
InputStream in = null;
|
||||
try {
|
||||
in = file.getInputStream();
|
||||
|
||||
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.contentType(file.getContentType())
|
||||
.contentLength(file.getSize())
|
||||
.key(path)
|
||||
.acl(ObjectCannedACL.PUBLIC_READ)
|
||||
.build();
|
||||
s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
|
||||
log.info("upload-copy 上传的位置:桶 - {},路径 - {}", bucketName, path);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (in != null) {
|
||||
try {
|
||||
in.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return bucketName + "/" + path;
|
||||
}
|
||||
|
||||
public InputStream download(String path) {
|
||||
if (!path.contains("/")) {
|
||||
throw new BusinessException("the.path.is.error");
|
||||
}
|
||||
int index = path.indexOf("/");
|
||||
String bucketName = path.substring(0, index);
|
||||
String objectName = path.substring(index + 1);
|
||||
return download(bucketName, objectName);
|
||||
}
|
||||
|
||||
public InputStream download(String bucketName, String objectName) {
|
||||
try {
|
||||
S3Client s3Client = getS3Client();
|
||||
GetObjectRequest objectRequest = GetObjectRequest
|
||||
.builder()
|
||||
.key(objectName)
|
||||
.bucket(bucketName)
|
||||
.build();
|
||||
|
||||
// ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
|
||||
ResponseBytes<GetObjectResponse> objectAsBytes = s3Client.getObjectAsBytes(objectRequest);
|
||||
byte[] data = objectAsBytes.asByteArray();
|
||||
log.info("download 下载图片位置:桶 - {},路径 - {}", bucketName, objectName);
|
||||
return new ByteArrayInputStream(data);
|
||||
|
||||
/*// Write the data to a local file.
|
||||
File myFile = new File("files/images.png");
|
||||
OutputStream os = new FileOutputStream(myFile);
|
||||
os.write(data);
|
||||
System.out.println("Successfully obtained bytes from an S3 object");
|
||||
os.close();
|
||||
return null;*/
|
||||
// return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
|
||||
} catch (Exception e) {
|
||||
log.error("");
|
||||
throw new BusinessException("");
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteObject(String path) {
|
||||
if (!path.contains("/")) {
|
||||
throw new BusinessException("The path is error!");
|
||||
}
|
||||
int index = path.indexOf("/");
|
||||
String bucketName = path.substring(0, index);
|
||||
String objectName = path.substring(index + 1);
|
||||
deleteObject(bucketName, objectName);
|
||||
}
|
||||
|
||||
public void deleteObject(String bucketName, String objectName) {
|
||||
try {
|
||||
S3Client s3Client = getS3Client();
|
||||
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest
|
||||
.builder()
|
||||
.key(objectName)
|
||||
.bucket(bucketName)
|
||||
.build();
|
||||
s3Client.deleteObject(deleteObjectRequest);
|
||||
log.info("Object " + objectName + " successfully removed from bucket " + bucketName);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
log.info("Error while removing object " + objectName + " from bucket " + bucketName + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public String getPreSignedUrl(String path, int expiry) {
|
||||
if (LocalCacheUtils.getPresignedUrlCache(path) != null) {
|
||||
return LocalCacheUtils.getPresignedUrlCache(path);
|
||||
} else {
|
||||
if (!path.contains("/")) {
|
||||
throw new BusinessException("The path is error!");
|
||||
}
|
||||
int index = path.indexOf("/");
|
||||
String bucketName = path.substring(0, index);
|
||||
String fileName = path.substring(index + 1);
|
||||
String preSignedUrl = getPreSignatureUrl(bucketName, fileName, expiry);
|
||||
LocalCacheUtils.setPresignedUrlCache(path, preSignedUrl);
|
||||
return preSignedUrl;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param keyName key名称: test/2022/06/123.pdf
|
||||
* @param signatureDurationTime 有效期 单位:秒
|
||||
* @return java.lang.String
|
||||
* @description: 生成预签名URL
|
||||
*/
|
||||
public String getPreSignatureUrl(String bucket, String keyName, Integer signatureDurationTime) {
|
||||
String preSignatureUrl = "";
|
||||
try {
|
||||
S3Presigner s3PreSigner = getS3PreSigner();
|
||||
S3Client s3Client = getS3Client();
|
||||
setObjectAcl(s3Client, bucket, keyName, ObjectCannedACL.PUBLIC_READ);
|
||||
|
||||
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
|
||||
.bucket(bucket)
|
||||
.key(keyName)
|
||||
.build();
|
||||
|
||||
//设置预签名URL可访问时间
|
||||
signatureDurationTime = Optional.ofNullable(signatureDurationTime)
|
||||
.map(item -> {
|
||||
if (item.intValue() > CommonConstant.Numbers.NUMBER_10080) {
|
||||
item = CommonConstant.Numbers.NUMBER_10080;
|
||||
}
|
||||
return item;
|
||||
})
|
||||
.orElse(CommonConstant.Numbers.NUMBER_10);
|
||||
GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder()
|
||||
.signatureDuration(Duration.ofMinutes(signatureDurationTime))
|
||||
.getObjectRequest(getObjectRequest)
|
||||
.build();
|
||||
|
||||
PresignedGetObjectRequest presignedGetObjectRequest =
|
||||
s3PreSigner.presignGetObject(getObjectPresignRequest);
|
||||
|
||||
preSignatureUrl = String.valueOf(presignedGetObjectRequest.url());
|
||||
} catch (Exception e) {
|
||||
log.error("生成预签名URL失败,异常:{}", e.getMessage());
|
||||
}
|
||||
return preSignatureUrl;
|
||||
}
|
||||
|
||||
public static void setObjectAcl(S3Client s3, String bucketName, String keyName, ObjectCannedACL acl) {
|
||||
PutObjectAclRequest aclRequest = PutObjectAclRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.key(keyName)
|
||||
.acl(acl)
|
||||
.build();
|
||||
s3.putObjectAcl(aclRequest);
|
||||
}
|
||||
public boolean doesObjectExist(String bucketName, String objectName) {
|
||||
try {
|
||||
S3Client s3Client = getS3Client();
|
||||
HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.key(objectName)
|
||||
.build();
|
||||
HeadObjectResponse headObjectResponse = s3Client.headObject(headObjectRequest);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.info("指定文件 {}/{} 不存在", bucketName, objectName);
|
||||
// 如果发生异常,说明文件不存在或者出现了其他错误
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public String base64UploadToPath(String base64, String bucketName, String path) {
|
||||
S3Client s3Client = getS3Client();
|
||||
String[] parts = base64.split(",");
|
||||
String imageType = parts[0].split("/")[1].split(";")[0];
|
||||
String base64Data = parts[1];
|
||||
|
||||
byte[] imageBytes = Base64.getDecoder().decode(base64Data);
|
||||
String fileName;
|
||||
if (!StringUtil.isNullOrEmpty(path)) {
|
||||
fileName = path + "." + imageType; // or any other image format
|
||||
} else {
|
||||
fileName = UUID.randomUUID() + "." + imageType;
|
||||
}
|
||||
|
||||
try (InputStream in = new ByteArrayInputStream(imageBytes)) {
|
||||
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.contentType("image/" + imageType)
|
||||
.contentLength((long) in.available())
|
||||
.key(fileName)
|
||||
.acl(ObjectCannedACL.PUBLIC_READ)
|
||||
.build();
|
||||
s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(in, in.available()));
|
||||
|
||||
log.info("base64UploadToPath 上传的位置:桶 - {},路径 - {}", bucketName, fileName);
|
||||
return bucketName + "/" + fileName;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null; // or throw an exception
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public List<String> listAllBucket() {
|
||||
S3Client s3Client = getS3Client();
|
||||
ListBucketsResponse listBucketsResponse = s3Client.listBuckets();
|
||||
List<Bucket> buckets = listBucketsResponse.buckets();
|
||||
return buckets.stream().map(Bucket::name).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -57,6 +57,7 @@ public class SendEmailUtil {
|
||||
* 登入模板id
|
||||
*/
|
||||
public static Long LOGIN_TEMPLATE_ID = 58020L;
|
||||
public static Long PORTFOLIO_REGISTER_ID = 124847L;
|
||||
/**
|
||||
* 修改密码模板id
|
||||
*/
|
||||
@@ -450,7 +451,143 @@ public class SendEmailUtil {
|
||||
}
|
||||
}
|
||||
|
||||
private final static Long QUESTIONNAIRE_FEEDBACK_EN_ID = 124151L;
|
||||
private final static Long QUESTIONNAIRE_FEEDBACK_CN_ID = 124156L;
|
||||
public static void questionnaireRelatedNotify(String userName, String email, String language){
|
||||
try {
|
||||
// 实例化一个认证对象
|
||||
Credential cred = new Credential(SECRET_ID, SECRET_KEy);
|
||||
HttpProfile httpProfile = new HttpProfile();
|
||||
httpProfile.setEndpoint("ses.tencentcloudapi.com");
|
||||
ClientProfile clientProfile = new ClientProfile();
|
||||
clientProfile.setHttpProfile(httpProfile);
|
||||
SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
|
||||
SendEmailRequest req = new SendEmailRequest();
|
||||
req.setFromEmailAddress(CODE_CREATE_SEND_ADDRESS);
|
||||
req.setDestination(new String[]{email});
|
||||
|
||||
// 根据邮件类型设置不同的主题和模板
|
||||
Template template = new Template();
|
||||
String subject = "Thank You for Completing the AiDA System Survey";
|
||||
template.setTemplateID(QUESTIONNAIRE_FEEDBACK_EN_ID);
|
||||
if (language.equals("CN")) {
|
||||
subject = "感谢您完成AiDA系统问卷调查";
|
||||
template.setTemplateID(QUESTIONNAIRE_FEEDBACK_CN_ID);
|
||||
}
|
||||
|
||||
JSONObject parameter = new JSONObject();
|
||||
parameter.put("userName", userName);
|
||||
|
||||
template.setTemplateData(parameter.toJSONString());
|
||||
|
||||
req.setSubject(subject);
|
||||
req.setTemplate(template);
|
||||
|
||||
// 发送邮件
|
||||
SendEmailResponse resp = client.SendEmail(req);
|
||||
log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
|
||||
} catch (TencentCloudSDKException e) {
|
||||
log.info("邮件发送失败###{}", e.toString());
|
||||
throw new BusinessException("failed.to.send.mail");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private final static Long NEW_USER_PAYMENT_NOTIFICATION_EN = 124889L;
|
||||
private final static Long NEW_USER_PAYMENT_NOTIFICATION_CN = 124888L;
|
||||
private final static Long RENEWAL_NOTIFICATION_FOR_OLD_USER_EN = 124892L;
|
||||
private final static Long RENEWAL_NOTIFICATION_FOR_OLD_USER_CN = 124891L;
|
||||
|
||||
public static void notificationForPaidUser(String receiverAddress, int emailType, String country, String userName, String date){
|
||||
try {
|
||||
// 实例化一个认证对象
|
||||
Credential cred = new Credential(SECRET_ID, SECRET_KEy);
|
||||
HttpProfile httpProfile = new HttpProfile();
|
||||
httpProfile.setEndpoint("ses.tencentcloudapi.com");
|
||||
ClientProfile clientProfile = new ClientProfile();
|
||||
clientProfile.setHttpProfile(httpProfile);
|
||||
SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
|
||||
SendEmailRequest req = new SendEmailRequest();
|
||||
req.setFromEmailAddress(SEND_ADDRESS);
|
||||
req.setDestination(new String[]{receiverAddress});
|
||||
|
||||
// 根据邮件类型设置不同的主题和模板
|
||||
String subject = "";
|
||||
Template template = new Template();
|
||||
JSONObject parameter = new JSONObject();
|
||||
switch (emailType) {
|
||||
// 新用户
|
||||
case 1:
|
||||
subject = "Welcome to AiDA!";
|
||||
if (country.equals("China")) {
|
||||
template.setTemplateID(NEW_USER_PAYMENT_NOTIFICATION_CN);
|
||||
}else {
|
||||
template.setTemplateID(NEW_USER_PAYMENT_NOTIFICATION_EN);
|
||||
}
|
||||
parameter.put("userName", userName);
|
||||
parameter.put("email", receiverAddress);
|
||||
break;
|
||||
// 续费用户
|
||||
case 2:
|
||||
subject = "Account renewal notification";
|
||||
if (country.equals("China")) {
|
||||
template.setTemplateID(RENEWAL_NOTIFICATION_FOR_OLD_USER_CN);
|
||||
}else {
|
||||
template.setTemplateID(RENEWAL_NOTIFICATION_FOR_OLD_USER_EN);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
parameter.put("userName", userName);
|
||||
parameter.put("date", date);
|
||||
template.setTemplateData(parameter.toJSONString());
|
||||
|
||||
req.setSubject(subject);
|
||||
req.setTemplate(template);
|
||||
|
||||
// 发送邮件
|
||||
SendEmailResponse resp = client.SendEmail(req);
|
||||
log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
|
||||
} catch (TencentCloudSDKException e) {
|
||||
log.info("邮件发送失败###{}", e.toString());
|
||||
throw new BusinessException("failed.to.send.mail");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static Boolean designWorksRegister(String userEmail, String randomVerifyCode) {
|
||||
try {
|
||||
// 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
|
||||
// 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
|
||||
Credential cred = new Credential(SECRET_ID, SECRET_KEy);
|
||||
// 实例化一个http选项,可选的,没有特殊需求可以跳过
|
||||
HttpProfile httpProfile = new HttpProfile();
|
||||
httpProfile.setEndpoint("ses.tencentcloudapi.com");
|
||||
// 实例化一个client选项,可选的,没有特殊需求可以跳过
|
||||
ClientProfile clientProfile = new ClientProfile();
|
||||
clientProfile.setHttpProfile(httpProfile);
|
||||
// 实例化要请求产品的client对象,clientProfile是可选的
|
||||
SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
|
||||
// 实例化一个请求对象,每个接口都会对应一个request对象
|
||||
SendEmailRequest req = new SendEmailRequest();
|
||||
|
||||
req.setFromEmailAddress(SEND_ADDRESS);
|
||||
req.setDestination(new String[]{userEmail});
|
||||
String subject = "Tourist registration";
|
||||
req.setSubject(subject);
|
||||
|
||||
req.setTemplate(contractTemplate(PORTFOLIO_REGISTER_ID, randomVerifyCode, null));
|
||||
|
||||
// 返回的resp是一个SendEmailResponse的实例,与请求对象对应
|
||||
SendEmailResponse resp = client.SendEmail(req);
|
||||
// 输出json格式的字符串回包
|
||||
log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
|
||||
return Boolean.TRUE;
|
||||
} catch (TencentCloudSDKException e) {
|
||||
log.info("邮件发送失败###{}", e.toString());
|
||||
throw new BusinessException("failed.to.send.mail");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user