vue.js js 雪花算法ID生成 vue.js之snowFlake算法
warning:
这篇文章距离上次修改已过204天,其中的内容可能已经有所变动。
// 引入vue和node的crypto模块
import Vue from 'vue'
const crypto = require('crypto')
// 定义snowFlake算法生成ID的Vue插件
const snowFlakeIdPlugin = {
install(Vue, options) {
// 扩展Vue实例方法
Vue.prototype.$snowFlakeId = () => {
const timeBits = 41 // 时间位数
const workerBits = 5 // 机器ID位数
const seqBits = 12 // 序列号位数
const timeLeftShift = workerBits + seqBits // 时间左移位数
const workerLeftShift = seqBits // 机器ID左移位数
const sequenceMask = -1 ^ (-1 << seqBits) // 序列号掩码
const workerMask = -1 ^ (-1 << workerBits) // 机器ID掩码
let timestampLeftShift = timeLeftShift
let lastTimestamp = 0 // 上一次时间戳
let sequence = 0 // 序列号
let workerId = options.workerId || 0 // 机器ID
return () => {
let timestamp = Date.now() // 当前时间戳
if (timestamp < lastTimestamp) {
// 如果时间戳小于上一次时间戳,则等待下一个毫秒
throw new Error('Clock moved backwards, refusing to generate id')
}
if (timestamp === lastTimestamp) {
// 同一毫秒内,序列号自增
sequence = (sequence + 1) & sequenceMask
if (sequence === 0) {
// 序列号达到最大值,等待下一毫秒
timestamp = tilNextMillis(lastTimestamp)
}
} else {
// 时间戳改变,序列号重置
sequence = 0
}
// 记录最后一次时间戳
lastTimestamp = timestamp
// 合并各部分
let id = ((timestamp - (timestamp % 1000)) << timestampLeftShift) |
(workerId << workerLeftShift) |
sequence
// 返回ID
return id
}
// 阻塞到下一毫秒
function tilNextMillis(lastTimestamp) {
let timestamp = Date.now()
while (timestamp <= lastTimestamp) {
timestamp = Date.now()
}
return timestamp
}
}
}
}
// 使插件生效
Vue.use(snowFlakeIdPlugin, { workerId: 1 })
// 示例:在Vue组件中使用
export default {
data() {
return {
id: null
}
},
created() {
this.id = this.$snowFlakeId()
console.log('Generated ID:', this.id)
}
}
这段代码定义了一个Vue插件,用于生成基于snowFlake算法的ID。插件在Vue中注册后,每个Vue实例都会有一个$snowFlakeId
方法,该方法可被调用以生成新的ID。这个例子中的snowFlake算法实现了时间戳、机器ID和序列号的组合,确保在分布式系统中每个ID都是唯一的。
评论已关闭