ShardingSphereService.java
2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.taover.repository.shardingsphere;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.taover.repository.autoconfigure.ShardingSphereKeyGeneratorConfiguration;
@Service
public class ShardingSphereService {
private Map<Long, List<ShardingInfoEntity>> CACHED_TABLE_SUFFIX_BY_TENANT = null;
private Map<String, ShardingKeyGeneratorExt> GENERATOR_HOLDER = new HashMap<String, ShardingKeyGeneratorExt>();
@Resource
private ShardingInfoRepository shardingInfoRepository;
private ShardingSphereKeyGeneratorConfiguration config;
public ShardingSphereService(ShardingSphereKeyGeneratorConfiguration config) {
this.config = config;
}
public List<Long> generateKeyList(String tableName, int number){
if(!GENERATOR_HOLDER.containsKey(tableName)) {
loadShardingKeyGenerator(tableName);
}
return GENERATOR_HOLDER.get(tableName).generateKeyList(number);
}
public List<ShardingInfoEntity> getShardingInfoMapByTenantId(Long tenantId) {
if(CACHED_TABLE_SUFFIX_BY_TENANT == null) {
loadCacheTableShardingInfoByTenantId();
}
return CACHED_TABLE_SUFFIX_BY_TENANT.get(tenantId);
}
private synchronized void loadCacheTableShardingInfoByTenantId() {
if(CACHED_TABLE_SUFFIX_BY_TENANT != null) {
return;
}
List<ShardingInfoEntity> dataList = this.shardingInfoRepository.findListBySql("1=1");
Map<Long, List<ShardingInfoEntity>> tempData = new HashMap<Long, List<ShardingInfoEntity>>();
for(ShardingInfoEntity item: dataList) {
List<ShardingInfoEntity> tempItem = tempData.getOrDefault(item.getTenantId(), new ArrayList<ShardingInfoEntity>());
tempItem.add(item);
tempData.put(item.getTenantId(), tempItem);
}
CACHED_TABLE_SUFFIX_BY_TENANT = tempData;
}
private synchronized void loadShardingKeyGenerator(String tableName) {
if(GENERATOR_HOLDER.containsKey(tableName)) {
return;
}
ShardingKeyGeneratorExt generator = new ShardingKeyGeneratorImpl();
generator.loalConfig(config);
GENERATOR_HOLDER.put(tableName, generator);
}
}