From 59b02b3f288baf7846936a403dc804ed2d250b9a Mon Sep 17 00:00:00 2001 From: xupei Date: Mon, 4 Nov 2024 10:49:29 +0800 Subject: [PATCH 01/12] to prod --- src/main/java/com/ai/da/common/config/MyTaskScheduler.java | 4 ++-- src/main/java/com/ai/da/common/task/AccountTask.java | 4 ++-- src/main/java/com/ai/da/common/task/PaypalTask.java | 2 +- src/main/java/com/ai/da/common/task/StripeTask.java | 2 +- src/main/resources/application.properties | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/ai/da/common/config/MyTaskScheduler.java b/src/main/java/com/ai/da/common/config/MyTaskScheduler.java index 61e964ea..95c55e9a 100644 --- a/src/main/java/com/ai/da/common/config/MyTaskScheduler.java +++ b/src/main/java/com/ai/da/common/config/MyTaskScheduler.java @@ -51,7 +51,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 qw = new QueryWrapper<>(); @@ -85,7 +85,7 @@ public class MyTaskScheduler { } } } -// @Scheduled(cron = "0 0 9 * * ?") + @Scheduled(cron = "0 0 9 * * ?") public void sendTrialOrderExcelToManagements() { // 获取前一天日期 LocalDate yesterday = LocalDate.now().minusDays(1); diff --git a/src/main/java/com/ai/da/common/task/AccountTask.java b/src/main/java/com/ai/da/common/task/AccountTask.java index 8b57b0f0..6950878d 100644 --- a/src/main/java/com/ai/da/common/task/AccountTask.java +++ b/src/main/java/com/ai/da/common/task/AccountTask.java @@ -26,7 +26,7 @@ public class AccountTask { accountService.refreshCreditsWeekly(); } -// @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes + @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes public void getPaidUser() { // 获取code-create 表中 指定日期之后 订单状态为wc-processing的订单 accountService.extendValidityForCC(); @@ -63,7 +63,7 @@ public class AccountTask { /** * 将Code-Create上注册的用户添加为AiDA的游客 */ -// @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes + @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes public void registerUserToVisitor() { accountService.registerUserToVisitor(); } diff --git a/src/main/java/com/ai/da/common/task/PaypalTask.java b/src/main/java/com/ai/da/common/task/PaypalTask.java index fa069971..865eaaa4 100644 --- a/src/main/java/com/ai/da/common/task/PaypalTask.java +++ b/src/main/java/com/ai/da/common/task/PaypalTask.java @@ -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 被执行......"); diff --git a/src/main/java/com/ai/da/common/task/StripeTask.java b/src/main/java/com/ai/da/common/task/StripeTask.java index d4a6fbaf..45d98997 100644 --- a/src/main/java/com/ai/da/common/task/StripeTask.java +++ b/src/main/java/com/ai/da/common/task/StripeTask.java @@ -22,7 +22,7 @@ public class StripeTask { @Resource private StripeService stripeService; -// @Scheduled(cron = "0/30 * * * * ?") + @Scheduled(cron = "0/30 * * * * ?") public void orderConfirm() throws SerializeException { // 查看超过30分钟以上仍未支付的订单 置为超时订单 diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 974fee23..8550475d 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -2,7 +2,7 @@ #spring.profiles.active=test #����application-prod�ļ�(��������) -#spring.profiles.active=prod +spring.profiles.active=prod #����application-dev�ļ�(��������) -spring.profiles.active=dev +#spring.profiles.active=dev From 903bafb24567738bf5cabdcac6aec43cce5192c8 Mon Sep 17 00:00:00 2001 From: xupei Date: Wed, 6 Nov 2024 17:27:16 +0800 Subject: [PATCH 02/12] =?UTF-8?q?=E7=AE=A1=E7=90=86=E5=91=98=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ConvenientInquiryController.java | 7 ++--- .../da/mapper/primary/TrialOrderMapper.java | 2 ++ .../com/ai/da/service/AccountService.java | 2 ++ .../da/service/ConvenientInquiryService.java | 4 +-- .../da/service/impl/AccountServiceImpl.java | 27 +++++++++++++++++++ .../impl/ConvenientInquiryServiceImpl.java | 26 ++++++++++++------ .../resources/mapper/primary/DesignMapper.xml | 2 +- .../mapper/primary/TrialOrderMapper.xml | 9 +++++++ 8 files changed, 65 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/ai/da/controller/ConvenientInquiryController.java b/src/main/java/com/ai/da/controller/ConvenientInquiryController.java index 7953b74a..25010c6d 100644 --- a/src/main/java/com/ai/da/controller/ConvenientInquiryController.java +++ b/src/main/java/com/ai/da/controller/ConvenientInquiryController.java @@ -122,14 +122,15 @@ public class ConvenientInquiryController { @ApiOperation("试用用户到正式用户的转化率") @GetMapping("/conversionRate") - public Response> conversionRate() { + public Response> conversionRate() { return Response.success(convenientInquiryService.conversionRate()); } @ApiOperation("试用用户国家/城市分布") @GetMapping("/trialUserCountry") - public Response>> trialUserCountry() { - return Response.success(convenientInquiryService.trialUserCountry()); + public Response>> trialUserCountry(@ApiParam(value = "startTime") @RequestParam(required = false) @Nullable String startTime, + @ApiParam(value = "endTime") @RequestParam(required = false) @Nullable String endTime) { + return Response.success(convenientInquiryService.trialUserCountry(startTime, endTime)); } @ApiOperation("添加用户") diff --git a/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java b/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java index 65709299..f39f8dee 100644 --- a/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java +++ b/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java @@ -3,6 +3,7 @@ package com.ai.da.mapper.primary; import com.ai.da.common.config.mybatis.plus.CommonMapper; import com.ai.da.mapper.primary.entity.TrialOrder; +import java.util.List; import java.util.Map; /** @@ -15,6 +16,7 @@ public interface TrialOrderMapper extends CommonMapper { Map countOfficialUser(); + List selectIdsByEmails(List emails); } diff --git a/src/main/java/com/ai/da/service/AccountService.java b/src/main/java/com/ai/da/service/AccountService.java index 5db57bc8..89610d8e 100644 --- a/src/main/java/com/ai/da/service/AccountService.java +++ b/src/main/java/com/ai/da/service/AccountService.java @@ -181,4 +181,6 @@ public interface AccountService extends IService { String updateNoLoginRequiredNew(NoLoginRequiredDTO noLoginRequiredDTO, HttpServletRequest request); void halfPricePromotion(); + + List getPaidCustomerEmail(); } diff --git a/src/main/java/com/ai/da/service/ConvenientInquiryService.java b/src/main/java/com/ai/da/service/ConvenientInquiryService.java index 49424df6..29b4a551 100644 --- a/src/main/java/com/ai/da/service/ConvenientInquiryService.java +++ b/src/main/java/com/ai/da/service/ConvenientInquiryService.java @@ -32,9 +32,9 @@ public interface ConvenientInquiryService extends IService { Map> getActiveUserFunc(String startTime, String endTime, List ids); - Map conversionRate(); + Map conversionRate(); - Map> trialUserCountry(); + Map> trialUserCountry(String startTime, String endTime); Boolean addUser(AccountAddDTO accountAddDTO); diff --git a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java index 0cf6e66e..1fc39366 100644 --- a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java @@ -571,6 +571,7 @@ public class AccountServiceImpl extends ServiceImpl impl account.setIsBeginner(1); account.setSystemUser(3); account.setValidStartTime(System.currentTimeMillis()); + account.setCountry(accountTrialDTO.getCountry()); if (link) { account.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli())); } else { @@ -583,6 +584,7 @@ public class AccountServiceImpl extends ServiceImpl impl account.setUserPassword("Third-000000"); account.setUserEmail(trialOrder.getEmail()); account.setLanguage(Language.ENGLISH.name()); + account.setCountry(accountTrialDTO.getCountry()); account.setValidStartTime(System.currentTimeMillis()); if (link) { account.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli())); @@ -1464,6 +1466,31 @@ public class AccountServiceImpl extends ServiceImpl impl } } + private static final String QUERY_PAID_CUSTOMER_EMAIL = "SELECT distinct c.email " + + "FROM `pmr_wc_order_stats` o " + + "inner join `pmr_wc_customer_lookup` c " + + "on o.customer_id = c.customer_id " + + "and o.net_total in (5000, 500, 250) " + + "and o.`status` != 'wc-failed' " + + "and c.email not in ('1779019091@qq.com', 'xupei3360@163.com', '1627315083@qq.com', 'gigiwu33@hotmail.com')"; + + public List getPaidCustomerEmail(){ + List paidCustomerEmail = new ArrayList<>(); + try (Connection connection = dataSource.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(QUERY_PAID_CUSTOMER_EMAIL)) { + try (ResultSet queryOrderResultSet = preparedStatement.executeQuery()) { + while (queryOrderResultSet.next()) { + paidCustomerEmail.add(queryOrderResultSet.getString("email")); + } + } + } catch (Exception e) { + // 记录异常并处理 + e.printStackTrace(); +// return null; + } + return paidCustomerEmail; + } + // 收集调查问卷的信息 @Override @Transactional(rollbackFor = Exception.class) diff --git a/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java b/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java index 2bad5969..1ce25b35 100644 --- a/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java @@ -392,7 +392,7 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl conversionRate() { + public Map conversionRate() { QueryWrapper queryWrapper = new QueryWrapper<>(); // 获取试用用户总数 @@ -402,22 +402,32 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl officialMaps = trialOrderMapper.countOfficialUser(); - Long trialToOfficial = officialMaps.get("count"); + List paidCustomerEmail = accountService.getPaidCustomerEmail(); + List paidTrialUsers = trialOrderMapper.selectIdsByEmails(paidCustomerEmail); + +// Map officialMaps = trialOrderMapper.countOfficialUser(); +// Long trialToOfficial = officialMaps.get("count"); // 计算转化率 - HashMap resp = new HashMap<>(); + HashMap resp = new HashMap<>(); resp.put("trialUserCount", totalTrials.floatValue()); - resp.put("trialToOfficialCount", trialToOfficial.floatValue()); - resp.put("conversionRate", new BigDecimal(trialToOfficial).divide(new BigDecimal(totalTrials), 2, RoundingMode.HALF_UP).floatValue()); - + resp.put("trialToOfficialCount", (float) paidTrialUsers.size()); + resp.put("conversionRate", new BigDecimal(paidTrialUsers.size()).divide(new BigDecimal(totalTrials), 6, RoundingMode.HALF_UP).floatValue()); + resp.put("paidTrialUser", paidTrialUsers); return resp; } // 试用用户地区统计 - public Map> trialUserCountry() { + public Map> trialUserCountry(String startTime, String endTime) { QueryWrapper queryWrapper = new QueryWrapper<>(); + if (!StringUtils.isNullOrEmpty(startTime)){ + queryWrapper.gt("create_time", startTime); + } + if (!StringUtils.isNullOrEmpty(endTime)){ + queryWrapper.lt("create_time", endTime); + } + queryWrapper.select("country, count(id) as count") .groupBy("country"); List> countryCount = trialOrderMapper.selectMaps(queryWrapper); diff --git a/src/main/resources/mapper/primary/DesignMapper.xml b/src/main/resources/mapper/primary/DesignMapper.xml index 5d970145..8a056a59 100644 --- a/src/main/resources/mapper/primary/DesignMapper.xml +++ b/src/main/resources/mapper/primary/DesignMapper.xml @@ -29,7 +29,7 @@ + + From 49f08d1191b23bb6b08cfee02c7f2fc6472de4bb Mon Sep 17 00:00:00 2001 From: xupei Date: Wed, 6 Nov 2024 17:51:51 +0800 Subject: [PATCH 03/12] =?UTF-8?q?=E7=AE=A1=E7=90=86=E5=91=98=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E4=BC=98=E5=8C=96-1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ConvenientInquiryController.java | 5 +++-- .../ai/da/mapper/primary/TrialOrderMapper.java | 3 --- .../da/model/dto/UserDesignStatisticDTO.java | 2 ++ .../da/service/ConvenientInquiryService.java | 2 +- .../impl/ConvenientInquiryServiceImpl.java | 18 ++++++++++++++++-- .../mapper/primary/TrialOrderMapper.xml | 9 --------- 6 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/ai/da/controller/ConvenientInquiryController.java b/src/main/java/com/ai/da/controller/ConvenientInquiryController.java index 25010c6d..ecc8fdd1 100644 --- a/src/main/java/com/ai/da/controller/ConvenientInquiryController.java +++ b/src/main/java/com/ai/da/controller/ConvenientInquiryController.java @@ -122,8 +122,9 @@ public class ConvenientInquiryController { @ApiOperation("试用用户到正式用户的转化率") @GetMapping("/conversionRate") - public Response> conversionRate() { - return Response.success(convenientInquiryService.conversionRate()); + public Response> conversionRate(@ApiParam(value = "startTime") @RequestParam(required = false) @Nullable String startTime, + @ApiParam(value = "endTime") @RequestParam(required = false) @Nullable String endTime) { + return Response.success(convenientInquiryService.conversionRate(startTime, endTime)); } @ApiOperation("试用用户国家/城市分布") diff --git a/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java b/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java index f39f8dee..d1de236e 100644 --- a/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java +++ b/src/main/java/com/ai/da/mapper/primary/TrialOrderMapper.java @@ -16,7 +16,4 @@ public interface TrialOrderMapper extends CommonMapper { Map countOfficialUser(); - List selectIdsByEmails(List emails); - - } diff --git a/src/main/java/com/ai/da/model/dto/UserDesignStatisticDTO.java b/src/main/java/com/ai/da/model/dto/UserDesignStatisticDTO.java index b0713077..0b087213 100644 --- a/src/main/java/com/ai/da/model/dto/UserDesignStatisticDTO.java +++ b/src/main/java/com/ai/da/model/dto/UserDesignStatisticDTO.java @@ -15,6 +15,8 @@ public class UserDesignStatisticDTO { private String isTrial; + private String credits; + private String trialOrderId; private String title; diff --git a/src/main/java/com/ai/da/service/ConvenientInquiryService.java b/src/main/java/com/ai/da/service/ConvenientInquiryService.java index 29b4a551..fa4210f4 100644 --- a/src/main/java/com/ai/da/service/ConvenientInquiryService.java +++ b/src/main/java/com/ai/da/service/ConvenientInquiryService.java @@ -32,7 +32,7 @@ public interface ConvenientInquiryService extends IService { Map> getActiveUserFunc(String startTime, String endTime, List ids); - Map conversionRate(); + Map conversionRate(String startTime, String endTime); Map> trialUserCountry(String startTime, String endTime); diff --git a/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java b/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java index 1ce25b35..819dc95d 100644 --- a/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/ConvenientInquiryServiceImpl.java @@ -392,9 +392,15 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl conversionRate() { + public Map conversionRate(String startTime, String endTime) { QueryWrapper queryWrapper = new QueryWrapper<>(); + if (!StringUtils.isNullOrEmpty(startTime)){ + queryWrapper.gt("create_time", startTime); + } + if (!StringUtils.isNullOrEmpty(endTime)){ + queryWrapper.lt("create_time", endTime); + } // 获取试用用户总数 queryWrapper.select("count(distinct email) as count"); @@ -403,7 +409,15 @@ public class ConvenientInquiryServiceImpl extends ServiceImpl paidCustomerEmail = accountService.getPaidCustomerEmail(); - List paidTrialUsers = trialOrderMapper.selectIdsByEmails(paidCustomerEmail); + QueryWrapper qw = new QueryWrapper<>(); + if (!StringUtils.isNullOrEmpty(startTime)){ + qw.gt("create_time", startTime); + } + if (!StringUtils.isNullOrEmpty(endTime)){ + qw.lt("create_time", endTime); + } + qw.in("email", paidCustomerEmail); + List paidTrialUsers = trialOrderMapper.selectList(qw); // Map officialMaps = trialOrderMapper.countOfficialUser(); // Long trialToOfficial = officialMaps.get("count"); diff --git a/src/main/resources/mapper/primary/TrialOrderMapper.xml b/src/main/resources/mapper/primary/TrialOrderMapper.xml index 01574ca3..827aa65d 100644 --- a/src/main/resources/mapper/primary/TrialOrderMapper.xml +++ b/src/main/resources/mapper/primary/TrialOrderMapper.xml @@ -24,13 +24,4 @@ ON a.user_email = b.email - - From 4408c0ecc68107a20f751e0f4396aee3b036941d Mon Sep 17 00:00:00 2001 From: xupei Date: Mon, 11 Nov 2024 10:29:06 +0800 Subject: [PATCH 04/12] to dev --- .../java/com/ai/da/common/config/MyTaskScheduler.java | 4 ++-- src/main/java/com/ai/da/common/task/AccountTask.java | 10 +++++----- src/main/java/com/ai/da/common/task/PaypalTask.java | 2 +- src/main/java/com/ai/da/common/task/StripeTask.java | 2 +- src/main/resources/application.properties | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/ai/da/common/config/MyTaskScheduler.java b/src/main/java/com/ai/da/common/config/MyTaskScheduler.java index 95c55e9a..61e964ea 100644 --- a/src/main/java/com/ai/da/common/config/MyTaskScheduler.java +++ b/src/main/java/com/ai/da/common/config/MyTaskScheduler.java @@ -51,7 +51,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 qw = new QueryWrapper<>(); @@ -85,7 +85,7 @@ public class MyTaskScheduler { } } } - @Scheduled(cron = "0 0 9 * * ?") +// @Scheduled(cron = "0 0 9 * * ?") public void sendTrialOrderExcelToManagements() { // 获取前一天日期 LocalDate yesterday = LocalDate.now().minusDays(1); diff --git a/src/main/java/com/ai/da/common/task/AccountTask.java b/src/main/java/com/ai/da/common/task/AccountTask.java index 6950878d..cfc65fd4 100644 --- a/src/main/java/com/ai/da/common/task/AccountTask.java +++ b/src/main/java/com/ai/da/common/task/AccountTask.java @@ -19,21 +19,21 @@ public class AccountTask { /** * 每周日晚上刷新 年付用户、月付用户的积分 */ - @Scheduled(cron = "59 59 23 ? * SUN") +// @Scheduled(cron = "59 59 23 ? * SUN") // @Scheduled(cron = "59 59 23 * * ?") public void refreshCreditsMonthly() { log.info("每周日晚11:59:59刷新付费用户积分为 6000"); accountService.refreshCreditsWeekly(); } - @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes +// @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes public void getPaidUser() { // 获取code-create 表中 指定日期之后 订单状态为wc-processing的订单 accountService.extendValidityForCC(); } // 每天凌晨0点执行一次 - @Scheduled(cron = "0 0 0 * * ?") +// @Scheduled(cron = "0 0 0 * * ?") public void cancelActivityBenefits() { // 1、查询当前所有参与了活动且过期的用户 List accountList = accountService.getExpiredUserBySystemUser(4); @@ -46,7 +46,7 @@ public class AccountTask { } // 每天检测正式用户到期情况,每天凌晨0点执行 - @Scheduled(cron = "0 0 0 * * ?") +// @Scheduled(cron = "0 0 0 * * ?") public void paidUserToVisitor() { // 1、查询当前已过期正式用户或试用用户 List accountList = accountService.getExpiredUserBySystemUser(1); @@ -63,7 +63,7 @@ public class AccountTask { /** * 将Code-Create上注册的用户添加为AiDA的游客 */ - @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes +// @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes public void registerUserToVisitor() { accountService.registerUserToVisitor(); } diff --git a/src/main/java/com/ai/da/common/task/PaypalTask.java b/src/main/java/com/ai/da/common/task/PaypalTask.java index 865eaaa4..fa069971 100644 --- a/src/main/java/com/ai/da/common/task/PaypalTask.java +++ b/src/main/java/com/ai/da/common/task/PaypalTask.java @@ -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 被执行......"); diff --git a/src/main/java/com/ai/da/common/task/StripeTask.java b/src/main/java/com/ai/da/common/task/StripeTask.java index 45d98997..d4a6fbaf 100644 --- a/src/main/java/com/ai/da/common/task/StripeTask.java +++ b/src/main/java/com/ai/da/common/task/StripeTask.java @@ -22,7 +22,7 @@ public class StripeTask { @Resource private StripeService stripeService; - @Scheduled(cron = "0/30 * * * * ?") +// @Scheduled(cron = "0/30 * * * * ?") public void orderConfirm() throws SerializeException { // 查看超过30分钟以上仍未支付的订单 置为超时订单 diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8550475d..974fee23 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -2,7 +2,7 @@ #spring.profiles.active=test #����application-prod�ļ�(��������) -spring.profiles.active=prod +#spring.profiles.active=prod #����application-dev�ļ�(��������) -#spring.profiles.active=dev +spring.profiles.active=dev From 5fe605c130a95c0927d8b5782a12fa174ec0ec97 Mon Sep 17 00:00:00 2001 From: xupei Date: Mon, 11 Nov 2024 10:45:57 +0800 Subject: [PATCH 05/12] =?UTF-8?q?=E9=95=BF=E8=BF=9E=E6=8E=A5=20=E5=85=B3?= =?UTF-8?q?=E9=97=AD=E6=97=A5=E5=BF=97=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/websocket/NotificationConnection.java | 15 +++++++++++++-- .../common/websocket/config/WebSocketConfig.java | 2 -- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java index 7dc7c7da..55e99ef3 100644 --- a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java +++ b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java @@ -38,12 +38,23 @@ public class NotificationConnection { } @OnClose - public void onClose() { + public void onClose(CloseReason reason) { websockets.remove(this); // 将当前的对象从集合中删除 - log.info("【连接断开】 用户为:{}", this.session); + log.info("【连接断开】 用户为:{}, 原因为{}", this.session, reason); // log.info("【连接断开】 总数为:{}", websockets.size()); } + /** + * 错误时调用 + * @param session 连接 + * @param throwable 异常 + */ + @OnError + public void onError(Session session, Throwable throwable) { + log.info("【连接异常】[session({}) 发生异常]", session, throwable); + websockets.remove(this); // 将当前的对象从集合中删除 + } + //收到了客户端消息执行的操作 @OnMessage public void onMessage(String text){ diff --git a/src/main/java/com/ai/da/common/websocket/config/WebSocketConfig.java b/src/main/java/com/ai/da/common/websocket/config/WebSocketConfig.java index df5b252b..9feb56a1 100644 --- a/src/main/java/com/ai/da/common/websocket/config/WebSocketConfig.java +++ b/src/main/java/com/ai/da/common/websocket/config/WebSocketConfig.java @@ -6,8 +6,6 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * Configuration of WebSocket - * - * @author db1995 */ @Configuration public class WebSocketConfig { From 546d1b4c44002a9a3d79a693e1d17f07bf701034 Mon Sep 17 00:00:00 2001 From: xupei Date: Mon, 11 Nov 2024 15:03:21 +0800 Subject: [PATCH 06/12] =?UTF-8?q?ws=20=E8=AE=BE=E7=BD=AEsession2=E5=88=86?= =?UTF-8?q?=E9=92=9F=E8=B6=85=E6=97=B6=EF=BC=8C=E4=BB=A5=E5=8F=8A=E5=BF=83?= =?UTF-8?q?=E8=B7=B3=E5=9B=9E=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../websocket/NotificationConnection.java | 45 ++++++++++++------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java index 55e99ef3..5f2c244d 100644 --- a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java +++ b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java @@ -16,11 +16,14 @@ import java.util.concurrent.ConcurrentHashMap; @Slf4j public class NotificationConnection { + //连接超时 + public static final long MAX_TIME_OUT = 2 * 60 * 1000; + static Map sessionMap = new ConcurrentHashMap<>(); private Session session; // 这里用ConcurrentHashMap 因为他是一个线程安全的Map - private static ConcurrentHashMap websockets = new ConcurrentHashMap<>(); + private static ConcurrentHashMap websockets = new ConcurrentHashMap<>(); //连接建立时执行的操作 /*@OnOpen public void onOpen(Session session){ @@ -31,7 +34,8 @@ public class NotificationConnection { @OnOpen public void onOpen(Session session, @PathParam("id") String id) { // 接收到前端传来的用户ID this.session = session; - websockets.put(Long.parseLong(id), this); //将ID作为key,当前的对象作为Value + this.session.setMaxIdleTimeout(MAX_TIME_OUT); + websockets.put(this, Long.parseLong(id)); //将ID作为key,当前的对象作为Value log.info("【建立连接】 用户为:{}", this.session); log.info("【建立连接】 用户Id为:{}", id); log.info("【建立连接】 总数为:{}", websockets.size()); @@ -39,27 +43,34 @@ public class NotificationConnection { @OnClose public void onClose(CloseReason reason) { - websockets.remove(this); // 将当前的对象从集合中删除 - log.info("【连接断开】 用户为:{}, 原因为{}", this.session, reason); + if (websockets.containsKey(this)) { + websockets.remove(this); // 将当前的对象从集合中删除 + log.info("【连接断开】 用户为:{}, sessionId: {}, 原因为{}", websockets.get(this), this.session.getId(), reason); + } + // log.info("【连接断开】 总数为:{}", websockets.size()); } /** * 错误时调用 - * @param session 连接 * @param throwable 异常 */ @OnError - public void onError(Session session, Throwable throwable) { - log.info("【连接异常】[session({}) 发生异常]", session, throwable); + public void onError(Throwable throwable) { + log.info("【连接异常】 用户为:{} , sessionId: {}", websockets.get(this), this.session.getId(), throwable); websockets.remove(this); // 将当前的对象从集合中删除 } //收到了客户端消息执行的操作 @OnMessage - public void onMessage(String text){ + public void onMessage(Session session, String text){ log.info("收到了一条消息:"+text); // return "已收到你的消息"; + if (text.equals("PING")){ + sendMsg("PONG", websockets.get(this)); + session.setMaxIdleTimeout(MAX_TIME_OUT); + } + } /*//连接关闭的时候执行的操作 @OnClose @@ -74,27 +85,31 @@ public class NotificationConnection { } }*/ - public void sendMsg(String message, Long userId) throws IOException { + public void sendMsg(String message, Long userId) { if (userId == null) { // 如果等于null则证明是群发 // 获取当前Map的一个迭代器,遍历Map的方式有很多种,看着来 // 这个就是遍历这个集合的过程.... - for (Map.Entry entry : websockets.entrySet()) { + for (Map.Entry entry : websockets.entrySet()) { // 获取每一个Entry实例 // 获取每一个Value,而这个Value就是WebSocket的实例 - NotificationConnection webSocket = entry.getValue(); + NotificationConnection webSocket = entry.getKey(); // 接下来就是遍历群发 log.info("广播消息 【给用户】 :{}发送消息【{}】", webSocket, message); - webSocket.session.getBasicRemote().sendText(message); // 发送!!!!!!!!! + try { + webSocket.session.getBasicRemote().sendText(message); // 发送!!!!!!!!! + } catch (IOException e) { + log.error("Failed to send message to session {}: {}", webSocket.session.getId(), e.getMessage()); + } } } else { // 如果不是群发,则判断ID,其余步骤一致 // 获取当前Map的一个迭代器,遍历Map的方式有很多种,看着来 // 这个就是遍历这个集合的过程.... - for (Map.Entry entry : websockets.entrySet()) { + for (Map.Entry entry : websockets.entrySet()) { // 获取每一个Entry实例 // 获取每一个Value,而这个Value就是WebSocket的实例 - NotificationConnection webSocket = entry.getValue(); + NotificationConnection webSocket = entry.getKey(); // 获取每一个Key,这个Key就是用户ID - Long key = entry.getKey(); + Long key = entry.getValue(); // 判断用户ID与当前的Key相等 if (userId.equals(key)) { log.info("私发消息 【给用户】 :{}发送消息【{}】", key, message); // 打印 From 4535fb7dfb370b66a8eff6f4a4ac872c4ca9c18e Mon Sep 17 00:00:00 2001 From: xupei Date: Mon, 11 Nov 2024 15:07:02 +0800 Subject: [PATCH 07/12] ws --- .../com/ai/da/service/impl/MessageCenterServiceImpl.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/com/ai/da/service/impl/MessageCenterServiceImpl.java b/src/main/java/com/ai/da/service/impl/MessageCenterServiceImpl.java index f6c1b874..74a19386 100644 --- a/src/main/java/com/ai/da/service/impl/MessageCenterServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/MessageCenterServiceImpl.java @@ -204,11 +204,7 @@ public class MessageCenterServiceImpl extends ServiceImpl Date: Mon, 11 Nov 2024 15:21:35 +0800 Subject: [PATCH 08/12] ws --- .../java/com/ai/da/common/websocket/NotificationConnection.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java index 5f2c244d..916f0713 100644 --- a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java +++ b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java @@ -34,7 +34,7 @@ public class NotificationConnection { @OnOpen public void onOpen(Session session, @PathParam("id") String id) { // 接收到前端传来的用户ID this.session = session; - this.session.setMaxIdleTimeout(MAX_TIME_OUT); +// this.session.setMaxIdleTimeout(MAX_TIME_OUT); websockets.put(this, Long.parseLong(id)); //将ID作为key,当前的对象作为Value log.info("【建立连接】 用户为:{}", this.session); log.info("【建立连接】 用户Id为:{}", id); From 8c20b51e13bf980c61a20e0cb46e09f67ca17a19 Mon Sep 17 00:00:00 2001 From: shahaibo <1023316923@qq.com> Date: Mon, 11 Nov 2024 16:04:26 +0800 Subject: [PATCH 09/12] =?UTF-8?q?TASK:=E8=B0=B7=E6=AD=8C=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../security/filter/AuthenticationFilter.java | 2 +- .../da/controller/ThirdPartyController.java | 7 ++ .../mapper/primary/entity/AccountExtend.java | 30 +++++++ .../primary/entity/AccountExtendMapper.java | 17 ++++ .../da/mapper/primary/entity/GoogleUser.java | 10 +++ .../ai/da/model/vo/GoogleTokenResponse.java | 10 +++ .../com/ai/da/service/AccountService.java | 3 + .../da/service/impl/AccountServiceImpl.java | 83 +++++++++++++++++++ 8 files changed, 161 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/ai/da/mapper/primary/entity/AccountExtend.java create mode 100644 src/main/java/com/ai/da/mapper/primary/entity/AccountExtendMapper.java create mode 100644 src/main/java/com/ai/da/mapper/primary/entity/GoogleUser.java create mode 100644 src/main/java/com/ai/da/model/vo/GoogleTokenResponse.java diff --git a/src/main/java/com/ai/da/common/security/filter/AuthenticationFilter.java b/src/main/java/com/ai/da/common/security/filter/AuthenticationFilter.java index 894a2231..a70bc51b 100644 --- a/src/main/java/com/ai/da/common/security/filter/AuthenticationFilter.java +++ b/src/main/java/com/ai/da/common/security/filter/AuthenticationFilter.java @@ -51,7 +51,7 @@ public class AuthenticationFilter extends OncePerRequestFilter { "/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","/api/stripe/trade/notify", - "/notification","/api/account/activateNewEmail" + "/notification","/api/account/activateNewEmail","/api/third/party/auth/google_callback" ); @Override diff --git a/src/main/java/com/ai/da/controller/ThirdPartyController.java b/src/main/java/com/ai/da/controller/ThirdPartyController.java index 0e7f95fd..e077fa8c 100644 --- a/src/main/java/com/ai/da/controller/ThirdPartyController.java +++ b/src/main/java/com/ai/da/controller/ThirdPartyController.java @@ -14,6 +14,7 @@ import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; import javax.validation.Valid; import java.security.cert.X509Certificate; @@ -114,4 +115,10 @@ public class ThirdPartyController { public Response updateNoLoginRequiredNew(@RequestBody NoLoginRequiredDTO noLoginRequiredDTO, HttpServletRequest request) { return Response.success(accountService.updateNoLoginRequiredNew(noLoginRequiredDTO, request)); } + + @CrossOrigin + @GetMapping("/auth/google_callback") + public Response googleCallback(@RequestParam("code") String code, HttpSession session) { + return Response.success(accountService.googleCallback(code, session)); + } } diff --git a/src/main/java/com/ai/da/mapper/primary/entity/AccountExtend.java b/src/main/java/com/ai/da/mapper/primary/entity/AccountExtend.java new file mode 100644 index 00000000..5742f0ec --- /dev/null +++ b/src/main/java/com/ai/da/mapper/primary/entity/AccountExtend.java @@ -0,0 +1,30 @@ +package com.ai.da.mapper.primary.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +@Data +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +@TableName("account_extend") +public class AccountExtend implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * ID + */ + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + private Long accountId; + + private String authType; + + private String auth; +} diff --git a/src/main/java/com/ai/da/mapper/primary/entity/AccountExtendMapper.java b/src/main/java/com/ai/da/mapper/primary/entity/AccountExtendMapper.java new file mode 100644 index 00000000..312fa810 --- /dev/null +++ b/src/main/java/com/ai/da/mapper/primary/entity/AccountExtendMapper.java @@ -0,0 +1,17 @@ +package com.ai.da.mapper.primary.entity; + +import com.ai.da.common.config.mybatis.plus.CommonMapper; + +import java.util.Date; +import java.util.List; + +/** + * Mapper 接口 + * + * @author easy-generator + * @since 2022-06-13 + */ +public interface AccountExtendMapper extends CommonMapper { + + +} diff --git a/src/main/java/com/ai/da/mapper/primary/entity/GoogleUser.java b/src/main/java/com/ai/da/mapper/primary/entity/GoogleUser.java new file mode 100644 index 00000000..b15410e8 --- /dev/null +++ b/src/main/java/com/ai/da/mapper/primary/entity/GoogleUser.java @@ -0,0 +1,10 @@ +package com.ai.da.mapper.primary.entity; + +import lombok.Data; + +@Data +public class GoogleUser { + private String id; + private String email; + private String name; +} diff --git a/src/main/java/com/ai/da/model/vo/GoogleTokenResponse.java b/src/main/java/com/ai/da/model/vo/GoogleTokenResponse.java new file mode 100644 index 00000000..f742d3c0 --- /dev/null +++ b/src/main/java/com/ai/da/model/vo/GoogleTokenResponse.java @@ -0,0 +1,10 @@ +package com.ai.da.model.vo; + +import lombok.Data; + +@Data +public class GoogleTokenResponse { + private String accessToken; + private String idToken; + +} diff --git a/src/main/java/com/ai/da/service/AccountService.java b/src/main/java/com/ai/da/service/AccountService.java index 5db57bc8..6e5c5b5f 100644 --- a/src/main/java/com/ai/da/service/AccountService.java +++ b/src/main/java/com/ai/da/service/AccountService.java @@ -11,6 +11,7 @@ import com.baomidou.mybatisplus.extension.service.IService; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; import java.util.List; import java.util.Map; @@ -181,4 +182,6 @@ public interface AccountService extends IService { String updateNoLoginRequiredNew(NoLoginRequiredDTO noLoginRequiredDTO, HttpServletRequest request); void halfPricePromotion(); + + String googleCallback(String code, HttpSession session); } diff --git a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java index 0cf6e66e..81bfd846 100644 --- a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java @@ -34,10 +34,12 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; +import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.math.BigDecimal; import java.sql.Connection; @@ -62,6 +64,9 @@ public class AccountServiceImpl extends ServiceImpl impl @Resource private AccountMapper accountMapper; + @Resource + private AccountExtendMapper accountExtendMapper; + @Resource private JWTTokenHelper jwtTokenHelper; @@ -1822,4 +1827,82 @@ public class AccountServiceImpl extends ServiceImpl impl log.info("邮箱绑定更改完成,用户id:{},新邮箱:{}", accountId, newMailbox); } + @Override + public String googleCallback(String code, HttpSession session) { + try { + log.info("code:" + code); + // 使用 code 获取 Google 用户信息 + GoogleUser googleUser = getGoogleUserFromCode(code); + log.info("googleUser:" + JSON.toJSONString(googleUser)); + + // 检查数据库中是否已有该用户 +// QueryWrapper qw = new QueryWrapper<>(); +// qw.lambda().eq(AccountExtend::getAuth, googleUser.getId()); +// List accountExtends = accountExtendMapper.selectList(qw); +// Account existingUser = findUserByGoogleId(googleUser.getId()); + return "Login successful"; +// if (CollectionUtil.isNotEmpty(accountExtends)) { +// // 用户已存在,直接登录 +//// session.setAttribute("user", existingUser); +// return "Login successful"; +// } else { +// // 用户不存在,创建新用户(自动注册) +//// User newUser = googleAuthService.registerNewUser(googleUser); +//// session.setAttribute("user", newUser); +// return "Registration and login successful"; +// } + } catch (Exception e) { + return "Error processing Google login: " + e.getMessage(); + } + } + + private static final String TOKEN_URL = "https://oauth2.googleapis.com/token"; + private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v3/userinfo"; + private static final String CLIENT_ID = "194770296147-njd68pm7tnapgonkj2h48mhf63n15n3f.apps.googleusercontent.com"; + private static final String CLIENT_SECRET = "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"; + private static final String REDIRECT_URI = "https://www.api.aida.com.hk/api/third/party/auth/google_callback"; + + public GoogleUser getGoogleUserFromCode(String code) { + // Step 1: Exchange code for access_token + String accessToken = getAccessToken(code); + log.info("accessToken" + accessToken); + + // Step 2: Use access_token to get Google User info + return getGoogleUserInfo(accessToken); + } + + private String getAccessToken(String code) { + RestTemplate restTemplate = new RestTemplate(); + Map params = new HashMap<>(); + params.put("client_id", CLIENT_ID); + params.put("client_secret", CLIENT_SECRET); + params.put("redirect_uri", REDIRECT_URI); + params.put("grant_type", "authorization_code"); + params.put("code", code); + + // 使用 RestTemplate 发起请求以获取 access_token + GoogleTokenResponse response = restTemplate.postForObject(TOKEN_URL, params, GoogleTokenResponse.class); + return response.getAccessToken(); + } + + private GoogleUser getGoogleUserInfo(String accessToken) { + RestTemplate restTemplate = new RestTemplate(); + String url = USER_INFO_URL + "?access_token=" + accessToken; + return restTemplate.getForObject(url, GoogleUser.class); + } + +// public User findUserByGoogleId(String googleId) { +// // 从数据库中根据 Google ID 查找用户 +// return userRepository.findByGoogleId(googleId); +// } + +// public User registerNewUser(GoogleUser googleUser) { +// // 创建并保存新用户 +// User newUser = new User(); +// newUser.setGoogleId(googleUser.getId()); +// newUser.setEmail(googleUser.getEmail()); +// newUser.setUsername(googleUser.getName()); +// return userRepository.save(newUser); +// } + } From 8da51a0a829d964b0eb77a65fb50c337689e0862 Mon Sep 17 00:00:00 2001 From: shahaibo <1023316923@qq.com> Date: Mon, 11 Nov 2024 16:08:49 +0800 Subject: [PATCH 10/12] =?UTF-8?q?TASK:=E8=B0=B7=E6=AD=8C=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/ai/da/service/impl/AccountServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java index 34efb6f2..2d826c03 100644 --- a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java @@ -1887,7 +1887,7 @@ public class AccountServiceImpl extends ServiceImpl impl private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v3/userinfo"; private static final String CLIENT_ID = "194770296147-njd68pm7tnapgonkj2h48mhf63n15n3f.apps.googleusercontent.com"; private static final String CLIENT_SECRET = "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"; - private static final String REDIRECT_URI = "https://www.api.aida.com.hk/api/third/party/auth/google_callback"; + private static final String REDIRECT_URI = "https://develop.api.aida.com.hk/api/third/party/auth/google_callback"; public GoogleUser getGoogleUserFromCode(String code) { // Step 1: Exchange code for access_token From 3cf05709125cd206db1693a77112610df6ffa7ca Mon Sep 17 00:00:00 2001 From: xupei Date: Mon, 11 Nov 2024 16:34:55 +0800 Subject: [PATCH 11/12] =?UTF-8?q?ws=20=E5=BC=95=E5=85=A5=E5=BF=83=E8=B7=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../websocket/NotificationConnection.java | 64 ++++++------------- 1 file changed, 21 insertions(+), 43 deletions(-) diff --git a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java index 916f0713..55bd53ad 100644 --- a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java +++ b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java @@ -17,38 +17,29 @@ import java.util.concurrent.ConcurrentHashMap; public class NotificationConnection { //连接超时 - public static final long MAX_TIME_OUT = 2 * 60 * 1000; - - static Map sessionMap = new ConcurrentHashMap<>(); + public static final long MAX_TIME_OUT = 3 * 60 * 1000; private Session session; + private Long userId; // 这里用ConcurrentHashMap 因为他是一个线程安全的Map - private static ConcurrentHashMap websockets = new ConcurrentHashMap<>(); - //连接建立时执行的操作 - /*@OnOpen - public void onOpen(Session session){ - sessionMap.put(session.getId(),session); - log.info("websocket is open, sessionId: {}",session.getId()); - }*/ + private static ConcurrentHashMap websockets = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session, @PathParam("id") String id) { // 接收到前端传来的用户ID this.session = session; -// this.session.setMaxIdleTimeout(MAX_TIME_OUT); - websockets.put(this, Long.parseLong(id)); //将ID作为key,当前的对象作为Value + this.userId = Long.valueOf(id); + this.session.setMaxIdleTimeout(MAX_TIME_OUT); + websockets.put(Long.parseLong(id), this); //将ID作为key,当前的对象作为Value log.info("【建立连接】 用户为:{}", this.session); log.info("【建立连接】 用户Id为:{}", id); - log.info("【建立连接】 总数为:{}", websockets.size()); + log.info("【当前连接总数】 为:{}", websockets.size()); } @OnClose public void onClose(CloseReason reason) { - if (websockets.containsKey(this)) { - websockets.remove(this); // 将当前的对象从集合中删除 - log.info("【连接断开】 用户为:{}, sessionId: {}, 原因为{}", websockets.get(this), this.session.getId(), reason); - } - -// log.info("【连接断开】 总数为:{}", websockets.size()); + log.info("【连接断开】 用户为:{}, sessionId: {}, 原因为{}", this.userId, this.session.getId(), reason); + log.info("【当前连接总数】 为:{}", websockets.size()); + websockets.remove(this.userId); // 将当前的对象从集合中删除 } /** @@ -57,42 +48,29 @@ public class NotificationConnection { */ @OnError public void onError(Throwable throwable) { - log.info("【连接异常】 用户为:{} , sessionId: {}", websockets.get(this), this.session.getId(), throwable); - websockets.remove(this); // 将当前的对象从集合中删除 + log.info("【连接异常】 用户为:{} , sessionId: {}", this.userId, this.session.getId(), throwable); + websockets.remove(this.userId); // 将当前的对象从集合中删除 + log.info("【当前连接总数】 为:{}", websockets.size()); } //收到了客户端消息执行的操作 @OnMessage - public void onMessage(Session session, String text){ - log.info("收到了一条消息:"+text); + public void onMessage(String text){ + log.info("收到了一条来自 {} 的消息:{}", this.userId, text); // return "已收到你的消息"; if (text.equals("PING")){ - sendMsg("PONG", websockets.get(this)); - session.setMaxIdleTimeout(MAX_TIME_OUT); + sendMsg("PONG", this.userId); } - } - /*//连接关闭的时候执行的操作 - @OnClose - public void onClose(Session session){ - sessionMap.remove(session.getId()); - log.info("websocket is close, sessionId: {}",session.getId()); - } - - public void sendMsg(String message) throws IOException { - for(String key:sessionMap.keySet()){ - sessionMap.get(key).getBasicRemote().sendText(message); - } - }*/ public void sendMsg(String message, Long userId) { if (userId == null) { // 如果等于null则证明是群发 // 获取当前Map的一个迭代器,遍历Map的方式有很多种,看着来 // 这个就是遍历这个集合的过程.... - for (Map.Entry entry : websockets.entrySet()) { + for (Map.Entry entry : websockets.entrySet()) { // 获取每一个Entry实例 // 获取每一个Value,而这个Value就是WebSocket的实例 - NotificationConnection webSocket = entry.getKey(); + NotificationConnection webSocket = entry.getValue(); // 接下来就是遍历群发 log.info("广播消息 【给用户】 :{}发送消息【{}】", webSocket, message); try { @@ -104,12 +82,12 @@ public class NotificationConnection { } else { // 如果不是群发,则判断ID,其余步骤一致 // 获取当前Map的一个迭代器,遍历Map的方式有很多种,看着来 // 这个就是遍历这个集合的过程.... - for (Map.Entry entry : websockets.entrySet()) { + for (Map.Entry entry : websockets.entrySet()) { // 获取每一个Entry实例 // 获取每一个Value,而这个Value就是WebSocket的实例 - NotificationConnection webSocket = entry.getKey(); + NotificationConnection webSocket = entry.getValue(); // 获取每一个Key,这个Key就是用户ID - Long key = entry.getValue(); + Long key = entry.getKey(); // 判断用户ID与当前的Key相等 if (userId.equals(key)) { log.info("私发消息 【给用户】 :{}发送消息【{}】", key, message); // 打印 From 74e6d5a1dae956905996b4ae17f0d837e0e0749c Mon Sep 17 00:00:00 2001 From: xupei Date: Mon, 11 Nov 2024 17:24:49 +0800 Subject: [PATCH 12/12] =?UTF-8?q?ws=20=E8=81=94=E8=B0=83=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../da/common/websocket/NotificationConnection.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java index 55bd53ad..595f268a 100644 --- a/src/main/java/com/ai/da/common/websocket/NotificationConnection.java +++ b/src/main/java/com/ai/da/common/websocket/NotificationConnection.java @@ -1,7 +1,10 @@ package com.ai.da.common.websocket; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSON; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.RequestParam; import javax.websocket.*; import javax.websocket.server.PathParam; @@ -55,11 +58,12 @@ public class NotificationConnection { //收到了客户端消息执行的操作 @OnMessage - public void onMessage(String text){ - log.info("收到了一条来自 {} 的消息:{}", this.userId, text); + public void onMessage(@RequestParam String text){ + Map textMap = JSONObject.parseObject(text, Map.class); + log.info("收到了一条来自 {} 的消息:{}, sessionId:{}", this.userId, textMap.get("text"), this.session.getId()); // return "已收到你的消息"; - if (text.equals("PING")){ - sendMsg("PONG", this.userId); + if (textMap.get("text").equals("PING")){ + sendMsg(JSON.toJSONString("PONG"), this.userId); } }