Redis生成分布式自增ID

匿名 (未验证) 提交于 2019-12-03 00:44:02

使用redis的RedisAtomicLong可以生成分布式自增的ID值。
SequenceFactory是封装的一个工具类,利用redisTemplate生成自增ID,实现如下:

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.support.atomic.RedisAtomicLong; import org.springframework.stereotype.Service;  import java.util.Date; import java.util.concurrent.TimeUnit;  @Service public class SequenceFactory {     @Autowired     RedisTemplate<String, String> redisTemplate;      /**      * @param key      * @param value      * @param expireTime      * @Title: set      * @Description: set cache.      */     public void set(String key, int value, Date expireTime) {         RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());         counter.set(value);         counter.expireAt(expireTime);     }      /**      * @param key      * @param value      * @param timeout      * @param unit      * @Title: set      * @Description: set cache.      */     public void set(String key, int value, long timeout, TimeUnit unit) {         RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());         counter.set(value);         counter.expire(timeout, unit);     }      /**      * @param key      * @return      * @Title: generate      * @Description: Atomically increments by one the current value.      */     public long generate(String key) {         RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());         return counter.incrementAndGet();     }      /**      * @param key      * @return      * @Title: generate      * @Description: Atomically increments by one the current value.      */     public long generate(String key, Date expireTime) {         RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());         counter.expireAt(expireTime);         return counter.incrementAndGet();     }      /**      * @param key      * @param increment      * @return      * @Title: generate      * @Description: Atomically adds the given value to the current value.      */     public long generate(String key, int increment) {         RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());         return counter.addAndGet(increment);     }      /**      * @param key      * @param increment      * @param expireTime      * @return      * @Title: generate      * @Description: Atomically adds the given value to the current value.      */     public long generate(String key, int increment, Date expireTime) {         RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());         counter.expireAt(expireTime);         return counter.addAndGet(increment);     } }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!