commit db6056a502ef620d00dacadaaa2e48e66f6ceb25 Author: chenqiang Date: Mon Jan 12 14:52:48 2026 +0800 first commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5a979af --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Kotlin ### +.kotlin diff --git a/META-INF/spring/spring.factories b/META-INF/spring/spring.factories new file mode 100644 index 0000000..642bba9 --- /dev/null +++ b/META-INF/spring/spring.factories @@ -0,0 +1,2 @@ +# Spring Boot Auto Configuration +org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.sycn.redisidgenerator.RedisIdGeneratorAutoConfiguration diff --git a/README.md b/README.md new file mode 100644 index 0000000..a00160d --- /dev/null +++ b/README.md @@ -0,0 +1,205 @@ +# Redis ID 生成器 + +## 工程介绍 + +Redis ID 生成器是一个基于 Spring Boot Starter 的组件,用于生成基于 Redis 的自增 ID。它的核心功能是: + +- 提供 `generateId(String key)` 方法,用于生成自增 ID +- 支持为不同的业务场景设置不同的 ID 计数器 +- 支持配置 ID 初始值 +- 基于 Redis 的 INCR 命令实现,保证 ID 的唯一性和单调性 + +## 技术栈 + +- Kotlin 1.9.25 +- Spring Boot 3.5.9 +- Jedis 5.1.0 +- Redis 6.0+ + +## 构建方法 + +### 前提条件 + +- JDK 17+ +- Gradle 8.5+ +- Redis 6.0+(运行时需要) + +### 构建步骤 + +1. 克隆或下载本工程到本地 + +2. 进入工程目录: + ```bash + cd redis-id-generator + ``` + +3. 执行构建命令: + ```bash + ./gradlew build --no-daemon + ``` + +4. 构建成功后,会在 `build/libs/` 目录下生成 `redis-id-generator-1.0.0.jar` 文件 + +## 引用方法 + +### 方法一:本地 JAR 包引用 + +1. 将构建生成的 `redis-id-generator-1.0.0.jar` 文件复制到目标工程的 `lib/` 目录(如果没有该目录,需要创建) + +2. 在目标工程的 `build.gradle.kts` 文件中添加依赖: + ```kotlin + dependencies { + // 其他依赖... + implementation(files("lib/redis-id-generator-1.0.0.jar")) + } + ``` + +### 方法二:Maven 仓库引用(未来支持) + +未来可以将 JAR 包发布到 Maven 仓库,然后通过坐标引用: + +```kotlin +dependencies { + // 其他依赖... + implementation("com.sycn:redis-id-generator:1.0.0") +} +``` + +## 配置说明 + +在目标工程的配置文件(如 `application-dev.properties` 或 `application-prod.properties`)中添加以下配置: + +```properties +# Redis ID生成器配置 +# Redis 服务器地址 +redis-id-generator.redis.host=localhost +# Redis 服务器端口 +redis-id-generator.redis.port=6379 +# Redis 密码(如果没有密码,留空) +redis-id-generator.redis.password= +# Redis 数据库索引 +redis-id-generator.redis.database=0 +# Redis 连接超时时间(毫秒) +redis-id-generator.redis.timeout=3000 +# 通用ID计数器的初始值 +redis-id-generator.id.initial-value=10000001 +# 各ID键的初始值映射(可选) +# redis-id-generator.id.initial-values.user=20000001 +# redis-id-generator.id.initial-values.order=30000001 +``` + +## 使用示例 + +### 1. 在 Spring Boot 配置类中启用 Redis ID 生成器 + +```kotlin +package com.example.config + +import com.sycn.redisidgenerator.RedisIdGeneratorProperties +import com.sycn.redisidgenerator.RedisIdGeneratorService +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration + +@Configuration +@EnableConfigurationProperties(RedisIdGeneratorProperties::class) +class RedisIdGeneratorConfig { + + @Bean + fun redisIdGeneratorService(properties: RedisIdGeneratorProperties): RedisIdGeneratorService { + val service = RedisIdGeneratorService(properties) + service.init() + return service + } +} +``` + +### 2. 在业务代码中使用 + +```kotlin +package com.example.controller + +import com.sycn.redisidgenerator.RedisIdGeneratorService +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController + +@RestController +@RequestMapping("/api") +class IdController( + private val redisIdGeneratorService: RedisIdGeneratorService +) { + + // 生成通用ID + @GetMapping("/id/generate") + fun generateId(): Long { + return redisIdGeneratorService.generateId() + } + + // 生成指定业务的ID + @GetMapping("/id/generate/user") + fun generateUserId(): Long { + return redisIdGeneratorService.generateId("user") + } + + // 生成订单ID + @GetMapping("/id/generate/order") + fun generateOrderId(): Long { + return redisIdGeneratorService.generateId("order") + } +} +``` + +## 核心实现原理 + +1. **连接管理**:使用 Jedis 连接池管理 Redis 连接,确保连接的高效利用 + +2. **ID 生成**:基于 Redis 的 INCR 命令实现自增,保证 ID 的唯一性和单调性 + +3. **初始值设置**:使用 Redis 的 SETNX 命令设置初始值,确保初始值只设置一次 + +4. **多业务支持**:为不同的业务场景使用不同的 Redis 键,实现业务隔离 + +5. **配置管理**:通过 Spring Boot 的配置属性机制,支持灵活的配置 + +## 注意事项 + +1. **Redis 依赖**:本组件运行时依赖 Redis 服务,必须确保 Redis 服务可用 + +2. **性能考虑**: + - ID 生成操作依赖网络 IO,性能会受到网络延迟的影响 + - 建议在生产环境中部署 Redis 集群,提高可用性和性能 + +3. **ID 冲突**: + - 基于 Redis 的 INCR 命令实现,天然保证 ID 的唯一性 + - 不同的业务场景使用不同的键,避免 ID 冲突 + +4. **初始值设置**: + - 初始值一旦设置,后续重启应用不会重置,因为 Redis 会持久化存储 + - 如果需要重置初始值,需要手动删除 Redis 中的对应键 + +## 故障处理 + +1. **Redis 连接失败**: + - 组件在初始化时会尝试连接 Redis,如果连接失败会抛出异常,应用启动失败 + - 确保 Redis 服务正常运行,网络连接畅通 + +2. **ID 生成失败**: + - 检查 Redis 服务是否正常 + - 检查网络连接是否畅通 + - 检查 Redis 权限是否正确 + +## 版本历史 + +### 1.0.0 + +- 初始版本 +- 实现基本的 ID 生成功能 +- 支持配置初始值 +- 支持多业务场景 + +## 联系我们 + +- 作者:chenqiang +- 邮箱:chenqiang@h024.cn +- 项目地址:[https://github.com/example/redis-id-generator](https://github.com/example/redis-id-generator) diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..8dd48ce --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,48 @@ +plugins { + id("java-library") + id("org.jetbrains.kotlin.jvm") version "1.9.25" +} + +group = "com.sycn" +version = "1.0.0" + +repositories { + mavenCentral() +} + +dependencies { + // Kotlin 标准库 + implementation(kotlin("stdlib")) + // Spring Boot 自动配置 + implementation("org.springframework.boot:spring-boot-starter:3.5.9") + // Jedis 客户端 + implementation("redis.clients:jedis:5.1.0") + // 配置处理器 + annotationProcessor("org.springframework.boot:spring-boot-configuration-processor:3.5.9") + // 测试依赖 + testImplementation("org.springframework.boot:spring-boot-starter-test:3.5.9") +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +kotlin { + jvmToolchain(17) +} + +// 禁用Kotlin守护进程,避免路径编码问题 +kotlin { + compilerOptions { + freeCompilerArgs.addAll("-Xdisable-default-scripting-plugin") + } +} + +// 打包配置 +tasks.withType { + manifest { + attributes["Implementation-Title"] = "Redis ID Generator Starter" + attributes["Implementation-Version"] = version + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/kotlin/com/sycn/redisidgenerator/RedisIdGeneratorAutoConfiguration.kt b/src/main/kotlin/com/sycn/redisidgenerator/RedisIdGeneratorAutoConfiguration.kt new file mode 100644 index 0000000..15a5ad2 --- /dev/null +++ b/src/main/kotlin/com/sycn/redisidgenerator/RedisIdGeneratorAutoConfiguration.kt @@ -0,0 +1,63 @@ +package com.sycn.redisidgenerator + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import jakarta.annotation.PostConstruct +import jakarta.annotation.PreDestroy + +/** + * Redis ID生成器自动配置类 + * 用于自动加载配置并初始化Redis ID生成器服务 + */ +@Configuration +@EnableConfigurationProperties(RedisIdGeneratorProperties::class) +class RedisIdGeneratorAutoConfiguration { + + /** + * 创建Redis ID生成器服务实例 + * @param properties 配置属性 + * @return RedisIdGeneratorService实例 + */ + @Bean + fun redisIdGeneratorService(properties: RedisIdGeneratorProperties): RedisIdGeneratorService { + return RedisIdGeneratorService(properties) + } + + /** + * Redis ID生成器生命周期管理器 + * 用于在应用启动时初始化服务,在应用关闭时关闭连接池 + */ + @Bean + fun redisIdGeneratorLifecycleManager(service: RedisIdGeneratorService): RedisIdGeneratorLifecycleManager { + return RedisIdGeneratorLifecycleManager(service) + } +} + +/** + * Redis ID生成器生命周期管理器 + * 处理服务的初始化和销毁 + */ +class RedisIdGeneratorLifecycleManager( + private val service: RedisIdGeneratorService +) { + + /** + * 初始化方法 + * 在Bean创建后执行,初始化Redis连接 + */ + @PostConstruct + fun init() { + service.init() + } + + /** + * 销毁方法 + * 在应用关闭时执行,关闭Redis连接池 + */ + @PreDestroy + fun destroy() { + service.close() + } +} diff --git a/src/main/kotlin/com/sycn/redisidgenerator/RedisIdGeneratorProperties.kt b/src/main/kotlin/com/sycn/redisidgenerator/RedisIdGeneratorProperties.kt new file mode 100644 index 0000000..55e01ac --- /dev/null +++ b/src/main/kotlin/com/sycn/redisidgenerator/RedisIdGeneratorProperties.kt @@ -0,0 +1,67 @@ +package com.sycn.redisidgenerator + +import org.springframework.boot.context.properties.ConfigurationProperties + +/** + * Redis ID生成器配置类 + * 用于读取主工程中以 redis-id-generator 为前缀的配置项 + */ +@ConfigurationProperties(prefix = "redis-id-generator") +class RedisIdGeneratorProperties { + + /** + * Redis连接配置 + */ + val redis = RedisConfig() + + /** + * ID初始值配置 + */ + val id = IdConfig() + + /** + * Redis连接配置内部类 + */ + class RedisConfig { + /** + * Redis主机地址 + */ + var host: String = "localhost" + + /** + * Redis端口 + */ + var port: Int = 6379 + + /** + * Redis密码 + */ + var password: String = "" + + /** + * Redis数据库索引 + */ + var database: Int = 0 + + /** + * Redis连接超时时间(毫秒) + */ + var timeout: Int = 3000 + } + + /** + * ID配置内部类 + */ + class IdConfig { + /** + * 通用ID计数器的初始值 + */ + var initialValue: Long = 10000001 + + /** + * 各ID键的初始值映射 + * 格式:key -> 初始值 + */ + val initialValues: MutableMap = mutableMapOf() + } +} diff --git a/src/main/kotlin/com/sycn/redisidgenerator/RedisIdGeneratorService.kt b/src/main/kotlin/com/sycn/redisidgenerator/RedisIdGeneratorService.kt new file mode 100644 index 0000000..0e13e3b --- /dev/null +++ b/src/main/kotlin/com/sycn/redisidgenerator/RedisIdGeneratorService.kt @@ -0,0 +1,121 @@ +package com.sycn.redisidgenerator + +import redis.clients.jedis.Jedis +import redis.clients.jedis.JedisPool +import redis.clients.jedis.JedisPoolConfig +import java.util.concurrent.ConcurrentHashMap + +/** + * Redis ID生成器服务 + * 基于Redis的自增操作实现ID生成功能 + */ +class RedisIdGeneratorService( + private val properties: RedisIdGeneratorProperties +) { + + /** + * Jedis连接池 + */ + private lateinit var jedisPool: JedisPool + + /** + * 已初始化的ID键缓存 + * 用于记录哪些键已经设置了初始值,避免重复设置 + */ + private val initializedKeys = ConcurrentHashMap.newKeySet() + + /** + * 初始化方法 + * 连接Redis并创建连接池 + */ + fun init() { + // 配置Jedis连接池 + val poolConfig = JedisPoolConfig() + poolConfig.maxTotal = 10 + poolConfig.maxIdle = 5 + poolConfig.minIdle = 1 + + // 创建Jedis连接池 + jedisPool = JedisPool( + poolConfig, + properties.redis.host, + properties.redis.port, + properties.redis.timeout, + properties.redis.password.takeIf { it.isNotEmpty() }, + properties.redis.database + ) + + // 测试连接 + try { + jedisPool.resource.use {jedis -> + jedis.ping() + } + println("Redis连接成功") + } catch (e: Exception) { + println("Redis连接失败: ${e.message}") + throw RuntimeException("Redis连接失败,无法初始化ID生成器", e) + } + } + + /** + * 生成ID的核心方法 + * @param key ID计数器的键名,可选,不传默认为空字符串 + * @return 生成的ID值 + */ + fun generateId(key: String = ""): Long { + // 使用通用键(空字符串)作为默认值 + val actualKey = if (key.isBlank()) "" else key + + // 生成Redis中的实际键名,添加前缀避免冲突 + val redisKey = if (actualKey.isBlank()) { + "id:generator:default" + } else { + "id:generator:$actualKey" + } + + // 从Jedis连接池获取连接 + return jedisPool.resource.use {jedis -> + // 检查并设置初始值 + if (!initializedKeys.contains(redisKey)) { + setInitialValue(jedis, redisKey, actualKey) + } + + // 执行自增操作并返回结果 + jedis.incr(redisKey) + } + } + + /** + * 设置ID计数器的初始值 + * @param jedis Jedis连接 + * @param redisKey Redis中的实际键名 + * @param originalKey 原始键名(用于查找配置的初始值) + */ + private fun setInitialValue(jedis: Jedis, redisKey: String, originalKey: String) { + // 查找对应键的初始值配置 + val initialValue = if (originalKey.isBlank()) { + // 使用通用初始值 + properties.id.initialValue + } else { + // 优先使用配置的对应键初始值,否则使用通用初始值 + properties.id.initialValues[originalKey] ?: properties.id.initialValue + } + + // 使用SETNX命令设置初始值,确保只设置一次 + val result = jedis.setnx(redisKey, initialValue.toString()) + + // 如果设置成功,或者键已经存在(可能其他实例已经设置),标记为已初始化 + initializedKeys.add(redisKey) + } + + /** + * 关闭方法 + * 关闭Jedis连接池 + */ + fun close() { + if (::jedisPool.isInitialized) { + jedisPool.close() + println("Redis连接池已关闭") + } + } +} diff --git a/src/main/resources/META-INF/spring/spring.factories b/src/main/resources/META-INF/spring/spring.factories new file mode 100644 index 0000000..642bba9 --- /dev/null +++ b/src/main/resources/META-INF/spring/spring.factories @@ -0,0 +1,2 @@ +# Spring Boot Auto Configuration +org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.sycn.redisidgenerator.RedisIdGeneratorAutoConfiguration