利用Redis實現自增ID生成


特別提示:本人博客部分有參考網絡其他博客,但均是本人親手編寫過並驗證通過。如發現博客有錯誤,請及時提出以免誤導其他人,謝謝!歡迎轉載,但記得標明文章出處: http://www.cnblogs.com/mao2080/

1、實現方法

Redis Incr 命令將 key 中儲存的數字值增一。如果 key 不存在,那么 key 的值會先被初始化為 0 ,然后再執行 INCR 操作。如果值包含錯誤的類型,或字符串類型的值不能表示為數字,那么返回一個錯誤。本操作的值限制在 64 位(bit)有符號數字表示之內。

2、相關代碼

a、工具方法

 1 /**
 2      * @Description: 獲取自增長值
 3      * @param key key
 4      * @return
 5      */
 6     public static Long getIncr(String key) {
 7         RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
 8         Long increment = entityIdCounter.getAndIncrement();
 9         entityIdCounter.expire(0, TimeUnit.SECONDS);
10         return increment;
11     }
12 
13     /**
14      * @Description: 初始化自增長值
15      * @param key key
16      * @param value 當前值
17      */
18     public void setIncr(String key, int value) {
19         RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
20         counter.set(value);
21         counter.expire(0, TimeUnit.SECONDS);
22     }

b、源碼分析

 1 private RedisAtomicLong(String redisCounter, RedisConnectionFactory factory, Long initialValue) {
 2         Assert.hasText(redisCounter, "a valid counter name is required");
 3         Assert.notNull(factory, "a valid factory is required");
 4 
 5         RedisTemplate<String, Long> redisTemplate = new RedisTemplate<String, Long>();
 6         redisTemplate.setKeySerializer(new StringRedisSerializer());
 7         redisTemplate.setValueSerializer(new GenericToStringSerializer<Long>(Long.class));
 8         redisTemplate.setExposeConnection(true);
 9         redisTemplate.setConnectionFactory(factory);
10         redisTemplate.afterPropertiesSet();
11 
12         this.key = redisCounter;
13         this.generalOps = redisTemplate;
14         this.operations = generalOps.opsForValue();
15 
16         if (initialValue == null) {
17             if (this.operations.get(redisCounter) == null) {
18                 set(0);
19             }
20         } else {
21             set(initialValue);
22         }
23     }

3、參考網站

http://www.runoob.com/redis/strings-incr.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM