0
点赞
收藏
分享

微信扫一扫

【分布式】Redis分布式之分布式唯一Id

waaagh 2022-03-12 阅读 218
说明

Redis生成分布式唯一Id的方式之一。

使用

示例代码:

package com.demo.redis.generate;

import org.redisson.api.RIdGenerator;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * RedisGenerateId
 *
 * @author 王思勤
 */
@Component
public class RedisGenerateId {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 获取 RIdGenerator
     *
     * @return 返回 值
     */
    public RIdGenerator getIdGenerator(String name) {
        RIdGenerator idGenerator = redissonClient.getIdGenerator(name);
        Assert.notNull(idGenerator, "idGenerator is null");
        return idGenerator;
    }

    /**
     * 初始化
     *
     * @param name           名称
     * @param initValue      初始值
     * @param allocationSize 分配的大小
     * @return 返回 是否成功
     */
    public boolean tryInit(String name, long initValue, long allocationSize) {
        return this.getIdGenerator(name).tryInit(initValue, allocationSize);
    }

    /**
     * 返回 下一个值
     *
     * @param name 名称
     * @return 返回 下一个ID的值
     */
    public long getNextId(String name) {
        return this.getIdGenerator(name).nextId();
    }
}

单元测试:

package com.demo.redis.generate;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.RIdGenerator;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;


@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisGenerateIdTest {

    private static final String NAME = "demo:redisGenerateId";

    @Resource
    private RedisGenerateId redisGenerateId;

    @Test
    public void test() {
        RIdGenerator idGenerator = redisGenerateId.getIdGenerator(NAME);
        idGenerator.tryInit(1, 1);
        long id = idGenerator.nextId();
        log.info("id = {}", id);
    }
}
举报

相关推荐

0 条评论