Lightweight Kotlin library for generating Snowflake IDs.
snowflake-id-core- core generator without framework dependenciessnowflake-id-spring-boot-starter- Spring Boot auto-configuration
Create a generator directly:
import io.snowflake.core.SnowflakeGenerator
val generator = SnowflakeGenerator(
dataCenterId = 1,
nodeId = 1,
)
val id = generator.nextId()Use the global access point:
import io.snowflake.core.Snowflake
import io.snowflake.core.SnowflakeGenerator
Snowflake.init(
SnowflakeGenerator(
dataCenterId = 1,
nodeId = 1,
),
)
val id = Snowflake.next()Add the starter dependency and configure the generator:
snowflake:
generator:
data-center-id: 1
node-id: 1If no SnowflakeGenerator bean is defined, the starter creates one automatically and initializes Snowflake.
import io.snowflake.core.Snowflake
import io.snowflake.core.SnowflakeGenerator
import org.springframework.stereotype.Service
@Service
class OrderService(
private val snowflakeGenerator: SnowflakeGenerator,
) {
fun nextOrderId(): Long = snowflakeGenerator.nextId()
fun nextGlobalOrderId(): Long = Snowflake.next()
}You can override the auto-configured generator with your own bean:
import io.snowflake.core.SnowflakeGenerator
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class SnowflakeConfig {
@Bean
fun snowflakeGenerator(): SnowflakeGenerator =
SnowflakeGenerator(
dataCenterId = 2,
nodeId = 3,
)
}./gradlew build