Search in sources :

Example 1 with Snowflake

use of cn.hutool.core.lang.Snowflake in project hutool by looly.

the class SnowflakeTest method snowflakeTest.

@Test
public void snowflakeTest() {
    HashSet<Long> hashSet = new HashSet<>();
    // 构建Snowflake,提供终端ID和数据中心ID
    Snowflake idWorker = new Snowflake(0, 0);
    for (int i = 0; i < 1000; i++) {
        long id = idWorker.nextId();
        hashSet.add(id);
    }
    Assert.assertEquals(1000L, hashSet.size());
}
Also used : Snowflake(cn.hutool.core.lang.Snowflake) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 2 with Snowflake

use of cn.hutool.core.lang.Snowflake in project hutool by looly.

the class SnowflakeTest method snowflakeTest1.

@Test
public void snowflakeTest1() {
    // 构建Snowflake,提供终端ID和数据中心ID
    Snowflake idWorker = new Snowflake(0, 0);
    long nextId = idWorker.nextId();
    Console.log(nextId);
}
Also used : Snowflake(cn.hutool.core.lang.Snowflake) Test(org.junit.Test)

Example 3 with Snowflake

use of cn.hutool.core.lang.Snowflake in project hutool by looly.

the class IdUtilTest method getSnowflakeTest.

@Test
public void getSnowflakeTest() {
    Snowflake snowflake = IdUtil.getSnowflake(1, 1);
    long id = snowflake.nextId();
    Assert.assertTrue(id > 0);
}
Also used : Snowflake(cn.hutool.core.lang.Snowflake) Test(org.junit.Test)

Example 4 with Snowflake

use of cn.hutool.core.lang.Snowflake in project hutool by looly.

the class IdUtilTest method snowflakeBenchTest.

@Test
@Ignore
public void snowflakeBenchTest() {
    final Set<Long> set = new ConcurrentHashSet<>();
    final Snowflake snowflake = IdUtil.getSnowflake(1, 1);
    // 线程数
    int threadCount = 100;
    // 每个线程生成的ID数
    final int idCountPerThread = 10000;
    final CountDownLatch latch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; i++) {
        ThreadUtil.execute(() -> {
            for (int i1 = 0; i1 < idCountPerThread; i1++) {
                long id = snowflake.nextId();
                set.add(id);
            // Console.log("Add new id: {}", id);
            }
            latch.countDown();
        });
    }
    // 等待全部线程结束
    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new UtilException(e);
    }
    Assert.assertEquals(threadCount * idCountPerThread, set.size());
}
Also used : ConcurrentHashSet(cn.hutool.core.collection.ConcurrentHashSet) UtilException(cn.hutool.core.exceptions.UtilException) Snowflake(cn.hutool.core.lang.Snowflake) CountDownLatch(java.util.concurrent.CountDownLatch) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

Snowflake (cn.hutool.core.lang.Snowflake)4 Test (org.junit.Test)4 ConcurrentHashSet (cn.hutool.core.collection.ConcurrentHashSet)1 UtilException (cn.hutool.core.exceptions.UtilException)1 HashSet (java.util.HashSet)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 Ignore (org.junit.Ignore)1