redis 實現分佈式唯一ID,其實這個也很簡單,主要使用redis String數據結構的 increment 方法。
原理:
使用increment方法,每次自加1,主要使用redis的高性能和單線程。
實現方式:
核心代碼如下,若是爲了保證長度一致,其實可以預先初始化值。現在的這個是從1,2.....逐漸遞增的
/**
* 注入Redis字符串模板
*/
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 當前的值 + 1
*
* @param key 鍵
* @return 返回操作之後的值
*/
public Long increment(final String key) {
return this.redisTemplate.opsForValue().increment(key, 1);
}
/**
* 當前的值加 + value
*
* @param key 鍵
* @param value 值
* @return 返回操作之後的值
*/
public Long incrementBy(final String key, final long value) {
return this.redisTemplate.opsForValue().increment(key, value);
}