Redis生成分佈式環境下自增ID

相信大家在分佈式系統一定會遇到如何生成唯一Id; 

uuid 可以但是,作爲數據庫主鍵很浪費性能(索引相關),

雪花算法可以, 但是很依賴於環境.

這裏推薦大家使用redis生成;

 


1. 需求明確

我們生成的Id組成爲, 時間戳+ 自增Id, 補0 

例如: 今天是2020.2.28 ,  補6個0 , 那麼生成的id範圍是20200228000001-202002289999999

2.技術選型

Redis中的RedisAtomicLong 具備原子性, 可以通過其incr方法進行遞增.

 

2. Id生成類

package com.dyhospital.cloudhis.common.redis.util;

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.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Description: 分佈式Id生成工廠
 * User: zhouzhou
 * Date: 2020-02-28
 * Time: 10:14
 */
@Component
public class IdGeneratorFactory {

    @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);
    }

    /**
     * 根據業務key, 長度, 獲取key, 以日期作爲前綴
     * <p>
     *     key = order, length = 5 ,當天日期2050年1月1日
     *     結果: 2050010100001
     * </p>
     * @param key
     * @param length
     * @return
     */
    public String generateIdByToday(String key, Integer length) {
        RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());

        long num = counter.incrementAndGet();
        counter.expireAt(getTodayEndTime());
        String id = getToday() +  String.format("%0" + length + "d", num);
        return id;

    }


    /**
     * @Title: getTodayEndTime 獲取今日最後的時間
     * @Description: Get the cache expire time.
     * @return
     */
    public static Date getTodayEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

    /**
     * @Title: getTodayEndTime 今天的日期格式: 20190101
     * @Description: Get the cache expire time.
     * @return
     */
    public static String getToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }

}

3. 我們來測試下

測試類如下:

   // ---------------------  分佈式自增Id 測試  ---------------------------
    @ApiOperation("根據key生成自增Id")
    @RequestMapping(value = "/getId/{key}", method = RequestMethod.GET)
    public GenericResponse<Long> getId(@PathVariable("key") String key) {
        logger.info("生成Id中");
        long generate = idGeneratorFactory.generate(key, IdGeneratorFactory.getTodayEndTime());
        return new GenericResponse<>(generate);
    }

    @ApiOperation("根據key生成自增Id,日期版")
    @RequestMapping(value = "/getIdByToday/{key}", method = RequestMethod.GET)
    public GenericResponse<String> getIdByToday(@PathVariable("key") String key) {
        logger.info("生成Id中");
        String id = idGeneratorFactory.generateIdByToday(key, 6);
        return new GenericResponse<>(id);
    }

測試結果如下: 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章