Skip to content

Commit

Permalink
feat(mumu): 新增雪花算法ID生成器
Browse files Browse the repository at this point in the history
  • Loading branch information
conifercone committed Dec 7, 2024
1 parent 0f03735 commit 6bfecca
Show file tree
Hide file tree
Showing 34 changed files with 132 additions and 218 deletions.
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,8 @@ spring-data-redis = { module = "org.springframework.data:spring-data-redis" }
resilience4j-retry = { module = "io.github.resilience4j:resilience4j-retry", version.ref = "resilience4jVersion" }
# https://mvnrepository.com/artifact/org.springframework.security/spring-security-rsa
spring-security-rsa = { module = "org.springframework.security:spring-security-rsa", version.ref = "springSecurityRsaVersion" }
# https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core
hibernate-core = { module = "org.hibernate.orm:hibernate-core" }

[bundles]
jackson = ["jackson-core", "jackson-databind", "jackson-annotations", "jackson-datatype-jsr310"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ public enum ResponseCode implements BaseResponse {
ROLE_IS_IN_USE_AND_CANNOT_BE_ARCHIVE(6034),
THE_ACCOUNT_ALREADY_HAS_AN_ADDRESS(6035),
UNABLE_TO_OBTAIN_CURRENT_REQUESTED_IP(6036),
ACCOUNT_ID_IS_NOT_ALLOWED_TO_BE_0(6037),
PERMISSION_DOES_NOT_EXIST(6038),
OCR_RECOGNITION_FAILED(6039),
TRANSLATION_FAILED(6040),
Expand Down
1 change: 0 additions & 1 deletion mumu-basis/src/main/resources/messages.properties
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@
6034=The role is in use and cannot be archived
6035=The account already has an address
6036=Unable to obtain current requested IP
6037=Account ID is not allowed to be 0
6038=Permission does not exist
6039=OCR recognition failed
6040=Translation failed
Expand Down
1 change: 0 additions & 1 deletion mumu-basis/src/main/resources/messages_en.properties
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@
6034=The role is in use and cannot be archived
6035=The account already has an address
6036=Unable to obtain current requested IP
6037=Account ID is not allowed to be 0
6038=Permission does not exist
6039=OCR recognition failed
6040=Translation failed
Expand Down
1 change: 0 additions & 1 deletion mumu-basis/src/main/resources/messages_ja.properties
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@
6034=使用中のロールをアーカイブできません
6035=アカウントの住所が既に存在します
6036=現在のリクエストのIPを取得できません
6037=アカウントIDは0にできません
6038=権限が存在しません
6039=OCR認識に失敗しました
6040=翻訳に失敗しました
Expand Down
1 change: 0 additions & 1 deletion mumu-basis/src/main/resources/messages_ko.properties
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@
6034=사용 중인 역할을 아카이브할 수 없음
6035=계정 주소가 이미 존재함
6036=현재 요청의 IP를 가져올 수 없음
6037=계정 ID는 0일 수 없음
6038=권한이 존재하지 않습니다
6039=OCR 인식에 실패했습니다
6040=번역에 실패했습니다
Expand Down
1 change: 0 additions & 1 deletion mumu-basis/src/main/resources/messages_ru.properties
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@
6034=Роль используется, архивирование невозможно
6035=Аккаунт с таким адресом уже существует
6036=Не удалось получить IP текущего запроса
6037=ID аккаунта не может быть равен 0
6038=Разрешение не существует
6039=Ошибка распознавания OCR
6040=Ошибка перевода
Expand Down
1 change: 0 additions & 1 deletion mumu-basis/src/main/resources/messages_zh.properties
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@
6034=角色正在使用无法归档
6035=账户已存在地址
6036=无法获取当前请求的IP
6037=账户ID不允许为0
6038=权限不存在
6039=OCR识别失败
6040=翻译失败
Expand Down
1 change: 0 additions & 1 deletion mumu-basis/src/main/resources/messages_zh_TW.properties
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@
6034=角色正在使用無法歸檔
6035=帳戶已存在地址
6036=無法獲取當前請求的IP
6037=帳戶ID不允許為0
6038=權限不存在
6039=OCR識別失敗
6040=翻譯失敗
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,10 @@
*/
package baby.mumu.authentication.client.api;

import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.micrometer.core.instrument.binder.grpc.ObservationGrpcClientInterceptor;
import java.time.Duration;
import java.util.Optional;
import java.util.function.Supplier;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.discovery.DiscoveryClient;
Expand Down Expand Up @@ -60,22 +56,6 @@ protected Optional<ManagedChannel> getManagedChannelUsePlaintext() {
}

protected boolean serviceAvailable() {
//noinspection DuplicatedCode
RetryConfig config = RetryConfig.custom()
.maxAttempts(5) // 最大尝试 5 次
.waitDuration(Duration.ofSeconds(2)) // 每次重试间隔 2 秒
.retryOnResult(result -> !(Boolean) result)
.build();

Retry retry = Retry.of(GRPC_AUTHENTICATION, config);

Supplier<Boolean> retryableSupplier = Retry.decorateSupplier(retry, () ->
!discoveryClient.getInstances(GRPC_AUTHENTICATION).isEmpty()
);
try {
return retryableSupplier.get();
} catch (Exception e) {
return false;
}
return !discoveryClient.getInstances(GRPC_AUTHENTICATION).isEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,6 @@
@Schema(description = "账户注册指令")
public class AccountRegisterCmd {

@Schema(description = "账户ID", requiredMode = RequiredMode.NOT_REQUIRED)
private Long id;

@Schema(description = "用户名", requiredMode = RequiredMode.REQUIRED)
@NotBlank(message = "{account.username.validation.not.blank}")
private String username;
Expand Down Expand Up @@ -98,12 +95,6 @@ public class AccountRegisterCmd {
@Data
public static class AccountAddressRegisterCmd {

/**
* 唯一主键
*/
@Schema(description = "账户地址ID", requiredMode = RequiredMode.NOT_REQUIRED)
private Long id;

/**
* 街道地址,包含门牌号和街道信息
*/
Expand Down Expand Up @@ -144,12 +135,6 @@ public static class AccountAddressRegisterCmd {
@Builder
public static class AccountSystemSettingsRegisterCmd {

/**
* 唯一主键
*/
@Schema(description = "账户系统设置ID", requiredMode = RequiredMode.NOT_REQUIRED)
private String id;

/**
* 系统设置标识
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
@Data
public class PermissionAddCmd {

private Long id;

@Size(max = 50, message = "{permission.code.validation.size}")
private String code;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@
@Data
public class RoleAddCmd {

private Long id;

@NotBlank
private String name;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@
import baby.mumu.basis.constants.AccountSystemSettingsDefaultValueConstants;
import baby.mumu.basis.exception.MuMuException;
import baby.mumu.basis.response.ResponseCode;
import baby.mumu.unique.client.api.PrimaryKeyGrpcService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Expand All @@ -84,7 +83,6 @@ public class AccountConvertor {
private final RoleConvertor roleConvertor;
private final AccountRepository accountRepository;
private final RoleRepository roleRepository;
private final PrimaryKeyGrpcService primaryKeyGrpcService;
private final AccountArchivedRepository accountArchivedRepository;
private final AccountAddressRepository accountAddressRepository;
private final AccountRoleRepository accountRoleRepository;
Expand All @@ -95,7 +93,7 @@ public class AccountConvertor {

@Autowired
public AccountConvertor(RoleConvertor roleConvertor, AccountRepository accountRepository,
RoleRepository roleRepository, PrimaryKeyGrpcService primaryKeyGrpcService,
RoleRepository roleRepository,
AccountArchivedRepository accountArchivedRepository,
AccountAddressRepository accountAddressRepository,
AccountRoleRepository accountRoleRepository,
Expand All @@ -106,7 +104,6 @@ public AccountConvertor(RoleConvertor roleConvertor, AccountRepository accountRe
this.roleConvertor = roleConvertor;
this.accountRepository = accountRepository;
this.roleRepository = roleRepository;
this.primaryKeyGrpcService = primaryKeyGrpcService;
this.accountArchivedRepository = accountArchivedRepository;
this.accountAddressRepository = accountAddressRepository;
this.accountRoleRepository = accountRoleRepository;
Expand Down Expand Up @@ -299,32 +296,18 @@ public Optional<AccountRedisDo> toAccountRedisDo(Account account) {
public Optional<Account> toEntity(AccountRegisterCmd accountRegisterCmd) {
return Optional.ofNullable(accountRegisterCmd).map(accountRegisterCmdNotNull -> {
Account account = AccountMapper.INSTANCE.toEntity(accountRegisterCmdNotNull);
Optional.ofNullable(account.getId()).ifPresentOrElse(id -> {
if (id == 0) {
throw new MuMuException(ResponseCode.ACCOUNT_ID_IS_NOT_ALLOWED_TO_BE_0);
}
}, () -> account.setId(primaryKeyGrpcService.snowflake()));
setRolesWithCodes(account, Optional.ofNullable(accountRegisterCmdNotNull.getRoleCodes())
.orElse(new ArrayList<>()));
Optional.ofNullable(account.getAddresses())
.filter(CollectionUtils::isNotEmpty)
.ifPresent(accountAddresses -> accountAddresses.forEach(accountAddress -> {
accountAddress.setUserId(account.getId());
if (accountAddress.getId() == null) {
accountAddress.setId(primaryKeyGrpcService.snowflake());
}
}));
.ifPresent(accountAddresses -> accountAddresses.forEach(
accountAddress -> accountAddress.setUserId(account.getId())));
Optional.ofNullable(account.getSystemSettings())
.ifPresentOrElse(
accountSystemSettings -> accountSystemSettings.forEach(accountSystemSettingsItem -> {
accountSystemSettingsItem.setUserId(account.getId());
if (accountSystemSettingsItem.getId() == null) {
accountSystemSettingsItem.setId(
String.valueOf(primaryKeyGrpcService.snowflake()));
}
}), () -> account.setSystemSettings(Collections.singletonList(
accountSystemSettings -> accountSystemSettings.forEach(
accountSystemSettingsItem -> accountSystemSettingsItem.setUserId(account.getId())),
() -> account.setSystemSettings(Collections.singletonList(
AccountSystemSettings.builder()
.id(String.valueOf(primaryKeyGrpcService.snowflake()))
.userId(
account.getId()).enabled(true).profile(
AccountSystemSettingsDefaultValueConstants.DEFAULT_ACCOUNT_SYSTEM_SETTINGS_PROFILE_VALUE)
Expand All @@ -333,7 +316,6 @@ public Optional<Account> toEntity(AccountRegisterCmd accountRegisterCmd) {
.enabled(true)
.build()))
);
accountRegisterCmdNotNull.setId(account.getId());
return account;
});
}
Expand Down Expand Up @@ -435,14 +417,7 @@ public Optional<AccountSystemSettings> toAccountSystemSettings(
public Optional<AccountSystemSettings> toAccountSystemSettings(
AccountAddSystemSettingsCmd accountAddSystemSettingsCmd) {
return Optional.ofNullable(accountAddSystemSettingsCmd)
.map(accountAddSystemSettingsCmdNotNull -> {
AccountSystemSettings accountSystemSettings = AccountMapper.INSTANCE.toAccountSystemSettings(
accountAddSystemSettingsCmdNotNull);
if (StringUtils.isBlank(accountSystemSettings.getId())) {
accountSystemSettings.setId(String.valueOf(primaryKeyGrpcService.snowflake()));
}
return accountSystemSettings;
});
.map(AccountMapper.INSTANCE::toAccountSystemSettings);
}

@API(status = Status.STABLE, since = "2.2.0")
Expand Down Expand Up @@ -485,14 +460,8 @@ public Optional<AccountSystemSettingsMongodbDo> resetAccountSystemSettingMongodb
@API(status = Status.STABLE, since = "2.0.0")
public Optional<AccountAddress> toEntity(
AccountAddAddressCmd accountAddAddressCmd) {
return Optional.ofNullable(accountAddAddressCmd).map(accountAddAddressCmdNonNull -> {
AccountAddress instanceEntity = AccountMapper.INSTANCE.toAccountAddress(accountAddAddressCmd);
if (instanceEntity.getId() == null) {
instanceEntity.setId(primaryKeyGrpcService.snowflake());
accountAddAddressCmdNonNull.setId(instanceEntity.getId());
}
return instanceEntity;
});
return Optional.ofNullable(accountAddAddressCmd).map(
AccountMapper.INSTANCE::toAccountAddress);
}

@API(status = Status.STABLE, since = "2.1.0")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import baby.mumu.basis.annotations.Metamodel;
import baby.mumu.basis.dataobject.jpa.JpaBasisDefaultDataObject;
import baby.mumu.unique.client.config.SnowflakeIdGenerator;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
Expand Down Expand Up @@ -51,6 +52,7 @@ public class AccountAddressDo extends JpaBasisDefaultDataObject {
* 唯一主键
*/
@Id
@SnowflakeIdGenerator
@Column(name = "id", nullable = false)
private Long id;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import baby.mumu.basis.dataobject.jpa.JpaBasisArchivableDataObject;
import baby.mumu.basis.enums.LanguageEnum;
import baby.mumu.basis.enums.SexEnum;
import baby.mumu.unique.client.config.SnowflakeIdGenerator;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
Expand Down Expand Up @@ -57,6 +58,7 @@ public class AccountDo extends JpaBasisArchivableDataObject {
* 账户id
*/
@Id
@SnowflakeIdGenerator
@Column(name = "id", nullable = false)
private Long id;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import baby.mumu.basis.dataobject.jpa.JpaMongodbBasisDefaultDataObject;
import baby.mumu.basis.enums.SystemThemeEnum;
import baby.mumu.basis.enums.SystemThemeModeEnum;
import baby.mumu.unique.client.config.SnowflakeIdGenerator;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.io.Serial;
Expand Down Expand Up @@ -59,6 +60,7 @@ public AccountSystemSettingsMongodbDo(String id, Long userId, String profile, St
}

@Id
@SnowflakeIdGenerator
@NotBlank
private String id;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
import baby.mumu.basis.exception.MuMuException;
import baby.mumu.basis.response.ResponseCode;
import baby.mumu.extension.translation.SimpleTextTranslation;
import baby.mumu.unique.client.api.PrimaryKeyGrpcService;
import jakarta.validation.Valid;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
Expand All @@ -61,19 +60,16 @@
@Component
public class PermissionConvertor {

private final PrimaryKeyGrpcService primaryKeyGrpcService;
private final PermissionRepository permissionRepository;
private final SimpleTextTranslation simpleTextTranslation;
private final PermissionArchivedRepository permissionArchivedRepository;
private final PermissionPathsRepository permissionPathsRepository;

@Autowired
public PermissionConvertor(PrimaryKeyGrpcService primaryKeyGrpcService,
PermissionRepository permissionRepository,
public PermissionConvertor(PermissionRepository permissionRepository,
ObjectProvider<SimpleTextTranslation> simpleTextTranslation,
PermissionArchivedRepository permissionArchivedRepository,
PermissionPathsRepository permissionPathsRepository) {
this.primaryKeyGrpcService = primaryKeyGrpcService;
this.permissionRepository = permissionRepository;
this.simpleTextTranslation = simpleTextTranslation.getIfAvailable();
this.permissionArchivedRepository = permissionArchivedRepository;
Expand Down Expand Up @@ -103,14 +99,8 @@ public Optional<PermissionDo> toDataObject(Permission permission) {

@API(status = Status.STABLE, since = "1.0.0")
public Optional<Permission> toEntity(PermissionAddCmd permissionAddCmd) {
return Optional.ofNullable(permissionAddCmd).map(permissionAddCmdNotNull -> {
Permission permission = PermissionMapper.INSTANCE.toEntity(permissionAddCmdNotNull);
if (permission.getId() == null) {
permission.setId(primaryKeyGrpcService.snowflake());
permissionAddCmdNotNull.setId(permission.getId());
}
return permission;
});
return Optional.ofNullable(permissionAddCmd)
.map(PermissionMapper.INSTANCE::toEntity);
}

@API(status = Status.STABLE, since = "1.0.0")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package baby.mumu.authentication.infrastructure.permission.gatewayimpl.database.dataobject;

import baby.mumu.basis.dataobject.jpa.JpaBasisArchivableDataObject;
import baby.mumu.unique.client.config.SnowflakeIdGenerator;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
Expand Down Expand Up @@ -50,6 +51,7 @@ public class PermissionDo extends JpaBasisArchivableDataObject {
* 权限id
*/
@Id
@SnowflakeIdGenerator
@Column(name = "id", nullable = false)
private Long id;

Expand Down
Loading

0 comments on commit 6bfecca

Please sign in to comment.