使用 Redis ,几行代码即可。
```
public class DistributedWorkerIdGenerator {
private static final String ID_WORKER_ID_INCREMENT_KEY = "ID_WORKER_ID_INCREMENT";
private static final int MAX_WORKER_ID = 64;
private static final int EXPIRE_SECONDS = 3600;
private static final String ID_WORKER_ID_PREFIX = "ID_WORKER_ID_";
/**
* 获取新的 workId
* 1.维护自增数字, 数字每次增加 1
* 2.如果 workerId 已经存在, 则循环获取新的 workerId
*
* @
param redisTemplate
* @
return workId
*/
Long acquireId(RedisTemplate<String, Object> redisTemplate) {
RedisAtomicLong redisAtomicLong = new RedisAtomicLong(ID_WORKER_ID_INCREMENT_KEY, redisTemplate.getConnectionFactory());
Long incrementIndex;
Long workerId;
for (int i = 0; i < MAX_WORKER_ID; i++) {
incrementIndex = redisAtomicLong.getAndIncrement();
workerId = incrementIndex % MAX_WORKER_ID;
if (redisTemplate.opsForValue().setIfAbsent(ID_WORKER_ID_PREFIX + workerId, workerId, EXPIRE_SECONDS, TimeUnit.SECONDS)) {
return workerId;
}
}
throw new ApplicationException("Generate workId failed");
}
/**
* 续签 workerId
* 服务实例需要通过定时任务续签, 定时任务的时间间隔需要小于过期时间
*
* @
param redisTemplate
* @
param workerId
*/
void renewalId(RedisTemplate<String, Object> redisTemplate, Long workerId) {
redisTemplate.expire(ID_WORKER_ID_PREFIX + workerId, EXPIRE_SECONDS, TimeUnit.SECONDS);
}
```