雪花算法生成全局唯一ID
package com.fwz.tproject.testfunction.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.fwz.tproject.testfunction.service.OrderService; /** * Controller * * @author 冯文哲 * @version 2018-06-11 */ @RestController @RequestMapping(value = "/test") public class MainController { @Autowired OrderService service; @RequestMapping(value = "test") public String test() { return service.getIDBySnowFlake(); } }
Service : IdGeneratorSnowflake OrderService
package com.fwz.tproject.testfunction.service; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.net.NetUtil; import cn.hutool.core.util.IdUtil; @Component public class IdGeneratorSnowflake { private long workerId = 0; private long datacenterId = 1; private Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId); private static final Logger log = LoggerFactory.getLogger(IdGeneratorSnowflake.class.getName()); // 依赖注入完成后执行该方法,进行一些初始化工作 @PostConstruct public void init() { try { workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr()); log.info("当前机器的workerId: {}", workerId); } catch (Exception e) { e.printStackTrace(); log.warn("当前机器的workerId获取失败", e); // 释放ID workerId = NetUtil.getLocalhostStr().hashCode(); } } // 使用默认机房号获取ID public synchronized long snowflakeId() { return snowflake.nextId(); } // 自己制定机房号获取ID public synchronized long snowflakeId(long workerId, long datacenterId) { Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId); return snowflake.nextId(); } /** * 生成的是不带-的字符审,类似于: 73a64edf935d4952a287739a66f96e06 * * @return */ public String simpleUUID() { return IdUtil.simpleUUID(); } /** * 生成的UUID是带-的字符串,类似于: b12b6401-6f9c-4351-b2b6-d8afc9ab9272 * * @return */ public String randomUUID() { return IdUtil.randomUUID(); } public static void main(String[] args) { IdGeneratorSnowflake f = new IdGeneratorSnowflake(); for (int i = 0; i < 1000; i++) { System.out.println(f.snowflakeId(0, 0)); } } }
package com.fwz.tproject.testfunction.service; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class OrderService { @Autowired private IdGeneratorSnowflake idGenerator; public String getIDBySnowFlake() { ExecutorService threadPool = Executors.newFixedThreadPool(5); for (int i = 1; i <= 20; i++) { threadPool.submit(() -> { System.out.println(idGenerator.snowflakeId()); }); } threadPool.shutdown(); return "he1lo snowflake"; } }
pom.xml
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-captcha</artifactId> <version>5.2.0</version> </dependency>