Mr.qian 1 lună în urmă
părinte
comite
c54ff65c43

+ 12 - 9
cif-service/src/main/java/com/txz/cif/configurer/sharding/ShardingSphereConfig.java

@@ -102,23 +102,26 @@ public class ShardingSphereConfig {
     }
 
     private TableRuleConfiguration getAccountFlowTableRuleConfiguration() {
-        TableRuleConfiguration result = new TableRuleConfiguration("c_account_flow", "ds${0..1}.c_account_flow_${202501..999912}");
-        result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("user_id", new UserIdShardingAlg()));
-        result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("create_time", new TimeShardingAlg()));
+        TableRuleConfiguration result = new TableRuleConfiguration("c_account_flow", "ds${0..1}.c_account_flow_${0..3}");
+        // 修改为按时间分库,按用户ID分表
+        result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("create_time", new TimeShardingAlg()));
+        result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("user_id", new UserIdShardingAlg()));
         return result;
     }
 
     private TableRuleConfiguration getFlowTableRuleConfiguration() {
-        TableRuleConfiguration result = new TableRuleConfiguration("c_flow", "ds${0..1}.c_flow_${202501..999912}");
-        result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("user_id", new UserIdShardingAlg()));
-        result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("create_time", new TimeShardingAlg()));
+        TableRuleConfiguration result = new TableRuleConfiguration("c_flow", "ds${0..1}.c_flow_${0..3}");
+        // 修改为按时间分库,按用户ID分表
+        result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("create_time", new TimeShardingAlg()));
+        result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("user_id", new UserIdShardingAlg()));
         return result;
     }
 
     private TableRuleConfiguration getRedEnvelopeTableRuleConfiguration() {
-        TableRuleConfiguration result = new TableRuleConfiguration("c_red_envelope", "ds${0..1}.c_red_envelope_${202501..999912}");
-        result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("user_id", new UserIdShardingAlg()));
-        result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("create_time", new TimeShardingAlg()));
+        TableRuleConfiguration result = new TableRuleConfiguration("c_red_envelope", "ds${0..1}.c_red_envelope_${0..3}");
+        // 修改为按时间分库,按用户ID分表
+        result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("create_time", new TimeShardingAlg()));
+        result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("user_id", new UserIdShardingAlg()));
         return result;
     }
 }

+ 4 - 10
cif-service/src/main/java/com/txz/cif/configurer/sharding/TimeShardingAlg.java

@@ -5,23 +5,17 @@ import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
 
 import java.util.Collection;
 import java.util.Date;
+import java.text.SimpleDateFormat;
 
 public class TimeShardingAlg implements PreciseShardingAlgorithm<Date> {
     
     @Override
     public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
-        Date dateValue = shardingValue.getValue();
-        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMM");
-        String tableSuffix = sdf.format(dateValue);
-        
-        for (String tableName : availableTargetNames) {
-            if (tableName.endsWith(tableSuffix)) {
-                return tableName;
-            }
-            
+        String dataSource = "ds" + Math.abs(new SimpleDateFormat("yyyyMMdd").format(shardingValue.getValue()).hashCode()) % 2;
+        if (availableTargetNames.contains(dataSource)) {
+            return dataSource;
         }
         // 兜底
         return availableTargetNames.iterator().next();
-        
     }
 }

+ 11 - 4
cif-service/src/main/java/com/txz/cif/configurer/sharding/UserIdShardingAlg.java

@@ -16,13 +16,20 @@ public class UserIdShardingAlg implements PreciseShardingAlgorithm<Long> {
         
         long shardValue = Long.parseLong(last4Digits);
         
+        // 按用户ID分表逻辑,分4张表
         String logicTableName = shardingValue.getLogicTableName();
         if ("c_account_flow".equals(logicTableName) || "c_flow".equals(logicTableName) || "c_red_envelope".equals(logicTableName)) {
-            String dataSource = "ds" + (shardValue % 2);
-            if (availableTargetNames.contains(dataSource)) {
-                return dataSource;
+            // 根据用户ID后四位对4取模确定表后缀
+            long tableIndex = shardValue % 4;
+            String tableSuffix = String.valueOf(tableIndex);
+            
+            for (String tableName : availableTargetNames) {
+                if (tableName.endsWith(tableSuffix)) {
+                    return tableName;
+                }
             }
-            // 兜底
+            
+            // 如果没找到匹配的表名,兜底使用第一个可用的表名
             return availableTargetNames.iterator().next();
         } else {
             return "dsdefault";

+ 0 - 30
cif-service/src/main/java/com/txz/cif/task/GeneralJob.java

@@ -19,7 +19,6 @@ import org.springframework.stereotype.Component;
 import tk.mybatis.mapper.entity.Condition;
 
 import javax.annotation.Resource;
-import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -191,35 +190,6 @@ public class GeneralJob {
         return ReturnT.SUCCESS;
     }
     
-    /**
-     * 定时创建分表任务
-     */
-    @XxlJob("createFutureTables")
-    public ReturnT<String> createFutureTables(String param) throws Exception {
-        try {
-            logger.info("【创建未来分表任务】开始");
-            
-            String currentMonthSuffix = DateUtil.format(new Date(), "yyyyMM");
-            
-            String[] tablePrefixes = {"c_account_flow_", "c_flow_", "c_red_envelope_"};
-            
-            String[] dataSources = {"cif_0", "cif_1"};
-            
-            for (String dataSource : dataSources) {
-                for (String tablePrefix : tablePrefixes) {
-                    String sql = "CREATE TABLE IF NOT EXISTS " + dataSource + "." + tablePrefix + currentMonthSuffix + " LIKE cif.c_account_flow";
-                    shardingMapper.createTable(sql);
-                }
-            }
-            
-            logger.info("【创建未来分表任务】完成");
-        } catch (Exception e) {
-            logger.error("【创建未来分表任务】异常:e{}", e);
-            return ReturnT.FAIL;
-        }
-        return ReturnT.SUCCESS;
-    }
-    
     
     public static void main(String[] args) {
         //        int quhao = 154;

+ 1 - 1
cif-service/src/main/resources/logback.xml

@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <configuration debug="false">
     <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
-    <property name="LOG_HOME" value="/var/logs/cif" />
+    <property name="LOG_HOME" value="./logs/cif" />
 <!--    <property name="port" value="${server.port}"/>-->
 <!--    <property resource="application.properties"/>-->
     <springProperty scope="context" name="port" source="server.port"/>

+ 2 - 3
cif-service/src/main/resources/mapper/AccountFlowMapper.xml

@@ -8,7 +8,7 @@
     <id column="id" jdbcType="BIGINT" property="id" />
     <result column="flow_id" jdbcType="BIGINT" property="flowId" />
     <result column="aliases" jdbcType="VARCHAR" property="aliases" />
-    <result column="biz_id" jdbcType="BIGINT" property="bizId" />
+    <result column="biz_id" jdbcType="VARCHAR" property="bizId" />
     <result column="biz_no" jdbcType="VARCHAR" property="bizNo" />
     <result column="account_id" jdbcType="BIGINT" property="accountId" />
     <result column="user_id" jdbcType="BIGINT" property="userId" />
@@ -25,8 +25,7 @@
   <select id="sumOccur" resultType="java.math.BigDecimal" >
     select sum(amount)  from  c_account_flow
     where type =  #{type} 
-    and create_time >= #{startTime}  
-    and #{endTime} > create_time  
+    and DATE(create_time) = CURDATE()
     and flow_type not in (4,5)  
     and aliases = #{aliases}
     and user_id = #{userId}

+ 34 - 21
cif-service/src/test/java/com/txz/cif/sharding/AccountFlowMapperTest.java

@@ -12,11 +12,12 @@ import org.springframework.test.context.web.WebAppConfiguration;
 
 import javax.annotation.Resource;
 import java.math.BigDecimal;
+import java.util.Calendar;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertNotNull;
 
 @RunWith(SpringRunner.class)
 @SpringBootTest(classes = CifApplication.class)
@@ -47,27 +48,39 @@ public class AccountFlowMapperTest {
     }
     
     @Test
-    public void testInsertAccountFlow() {
-        AccountFlow accountFlow = AccountFlow.builder()
-                .aliases("101")
-                .transTime(new Date())
-                .bizNo("TEST001")
-                .flowId(1001L)
-                .bizId("BIZ001")
-                .accountId(10001L)
-                .userId(1L)
-                .amount(new BigDecimal("100.00"))
-                .balance(new BigDecimal("500.00"))
-                .freezeAmount(new BigDecimal("50.00"))
-                .type(1)
-                .bizType(1001)
-                .flowType(1)
-                .createTime(new Date())
-                .build();
+    public void testInsert() {
         
-        accountFlowMapper.insert(accountFlow);
-        accountFlow.setUserId(2L);
-        accountFlowMapper.insert(accountFlow);
+        AccountFlow accountFlow = new AccountFlow();
+        accountFlow.setAliases("test");
+        accountFlow.setTransTime(new Date());
+        accountFlow.setBizNo("test123");
+        accountFlow.setFlowId(1L);
+        accountFlow.setBizId("biz123");
+        accountFlow.setAccountId(1L);
+        accountFlow.setAmount(new BigDecimal("100"));
+        accountFlow.setBalance(new BigDecimal("200"));
+        accountFlow.setFreezeAmount(new BigDecimal("50"));
+        accountFlow.setType(1);
+        accountFlow.setBizType(1001);
+        accountFlow.setFlowType(1);
+        accountFlow.setCreateTime(new Date());
+        
+        for (long i = 1; i < 5L; i++) {
+            accountFlow.setUserId(i);
+            accountFlowMapper.insert(accountFlow);
+        }
+        
+        // 前一天
+        Calendar calendar = Calendar.getInstance();
+        calendar.add(Calendar.DAY_OF_YEAR, -1);
+        Date time = calendar.getTime();
+        accountFlow.setTransTime(time);
+        accountFlow.setCreateTime(time);
+        
+        for (long i = 1; i < 5L; i++) {
+            accountFlow.setUserId(i);
+            accountFlowMapper.insert(accountFlow);
+        }
     }
     
     @Test

+ 0 - 33
cif-service/src/test/java/com/txz/cif/sharding/GeneralJobTest.java

@@ -1,33 +0,0 @@
-package com.txz.cif.sharding;
-
-import com.txz.cif.CifApplication;
-import com.txz.cif.task.GeneralJob;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.test.context.web.WebAppConfiguration;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(classes = CifApplication.class)
-@WebAppConfiguration
-@TestPropertySource(properties = {
-        "spring.cloud.nacos.discovery.group=qly",
-        "dubbo.registry.group=qly",
-        "dev.nacos=124.222.152.234:8848",
-        "mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl",
-        "mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl"
-})
-public class GeneralJobTest {
-    
-    @Autowired
-    private GeneralJob generalJob;
-    
-    @Test
-    public void testCreateFutureTables() throws Exception {
-        generalJob.createFutureTables("");
-    }
-    
-}