滴滴的分布式ID生成器(Tinyid),好用的一批

滴滴的分布式ID生成器(Tinyid),好用的一批

作者:佚名 2020-11-04 14:40:26

数据库

其他数据库

分布式 Tinyid是滴滴开发的一款分布式ID系统,Tinyid是在美团(Leaf)的leaf-segment算法基础上升级而来,不仅支持了数据库多主节点模式,还提供了tinyid-client客户端的接入方式,使用起来更加方便。

 不了解分布式ID生成器的同学,先复习一下之前的 《9种分布式ID生成方式》

Tinyid是滴滴开发的一款分布式ID系统,Tinyid是在美团(Leaf)的leaf-segment算法基础上升级而来,不仅支持了数据库多主节点模式,还提供了tinyid-client客户端的接入方式,使用起来更加方便。但和美团(Leaf)不同的是,Tinyid只支持号段一种模式不支持雪花模式。

Tinyid的特性

  •  全局唯一的long型ID
  •  趋势递增的id
  •  提供 http 和 java-client 方式接入
  •  支持批量获取ID
  •  支持生成1,3,5,7,9…序列的ID
  •  支持多个db的配置

适用场景:只关心ID是数字,趋势递增的系统,可以容忍ID不连续,可以容忍ID的浪费

不适用场景:像类似于订单ID的业务,因生成的ID大部分是连续的,容易被扫库、或者推算出订单量等信息

Tinyid原理

Tinyid是基于号段模式实现,再简单啰嗦一下号段模式的原理:就是从数据库批量的获取自增ID,每次从数据库取出一个号段范围,例如 (1,1000] 代表1000个ID,业务服务将号段在本地生成1~1000的自增ID并加载到内存.。

Tinyid会将可用号段加载到内存中,并在内存中生成ID,可用号段在首次获取ID时加载,如当前号段使用达到一定比例时,系统会异步的去加载下一个可用号段,以此保证内存中始终有可用号段,以便在发号服务宕机后一段时间内还有可用ID。

原理图大致如下图:

Tinyid原理图

Tinyid实现

Tinyid的GitHub地址 :https://github.com/didi/tinyid.git

Tinyid提供了两种调用方式,一种基于Tinyid-server提供的http方式,另一种Tinyid-client客户端方式。不管使用哪种方式调用,搭建Tinyid都必须提前建表tiny_id_info、tiny_id_token。 

  1. CREATE TABLE `tiny_id_info` (  
  2.   `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键',  
  3.   `biz_type` varchar(63) NOT NULL DEFAULT '' COMMENT '业务类型,唯一',  
  4.   `begin_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '开始id,仅记录初始值,无其他含义。初始化时begin_id和max_id应相同',  
  5.   `max_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '当前最大id',  
  6.   `step` int(11) DEFAULT '0' COMMENT '步长',  
  7.   `delta` int(11) NOT NULL DEFAULT '1' COMMENT '每次id增量',  
  8.   `remainder` int(11) NOT NULL DEFAULT '0' COMMENT '余数',  
  9.   `create_time` timestamp NOT NULL DEFAULT '2010-01-01 00:00:00' COMMENT '创建时间',  
  10.   `update_time` timestamp NOT NULL DEFAULT '2010-01-01 00:00:00' COMMENT '更新时间',  
  11.   `version` bigint(20) NOT NULL DEFAULT '0' COMMENT '版本号',  
  12.   PRIMARY KEY (`id`), 
  13.   UNIQUE KEY `uniq_biz_type` (`biz_type`)  
  14. ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT 'id信息表';  
  15. CREATE TABLE `tiny_id_token` (  
  16.   `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',  
  17.   `token` varchar(255) NOT NULL DEFAULT '' COMMENT 'token',  
  18.   `biz_type` varchar(63) NOT NULL DEFAULT '' COMMENT '此token可访问的业务类型标识',  
  19.   `remark` varchar(255) NOT NULL DEFAULT '' COMMENT '备注',  
  20.   `create_time` timestamp NOT NULL DEFAULT '2010-01-01 00:00:00' COMMENT '创建时间',  
  21.   `update_time` timestamp NOT NULL DEFAULT '2010-01-01 00:00:00' COMMENT '更新时间',  
  22.   PRIMARY KEY (`id`)  
  23. ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT 'token信息表';  
  24. INSERT INTO `tiny_id_info` (`id`, `biz_type`, `begin_id`, `max_id`, `step`, `delta`, `remainder`, `create_time`, `update_time`, `version`)  
  25. VALUES  
  26.  (1, 'test', 1, 1, 100000, 1, 0, '2018-07-21 23:52:58', '2018-07-22 23:19:27', 1);  
  27. INSERT INTO `tiny_id_info` (`id`, `biz_type`, `begin_id`, `max_id`, `step`, `delta`, `remainder`, `create_time`, `update_time`, `version`)  
  28. VALUES  
  29.  (2, 'test_odd', 1, 1, 100000, 2, 1, '2018-07-21 23:52:58', '2018-07-23 00:39:24', 3);  
  30. INSERT INTO `tiny_id_token` (`id`, `token`, `biz_type`, `remark`, `create_time`, `update_time`)  
  31. VALUES  
  32.  (1, '0f673adf80504e2eaa552f5d791b644c', 'test', '1', '2017-12-14 16:36:46', '2017-12-14 16:36:48');  
  33. INSERT INTO `tiny_id_token` (`id`, `token`, `biz_type`, `remark`, `create_time`, `update_time`)  
  34. VALUES  
  35.  (2, '0f673adf80504e2eaa552f5d791b644c', 'test_odd', '1', '2017-12-14 16:36:46', '2017-12-14 16:36:48'); 

tiny_id_info表是具体业务方号段信息数据表

max_id :号段的最大值

step:步长,即为号段的长度

biz_type:业务类型

号段获取对max_id字段做一次update操作,update max_id= max_id + step,更新成功则说明新号段获取成功,新的号段范围是(max_id ,max_id +step]。

tiny_id_token是一个权限表,表示当前token可以操作哪些业务的号段信息。

修改tinyid-server中  \offline\application.properties 文件配置数据库,由于tinyid支持数据库多master模式,可以配置多个数据库信息。启动 TinyIdServerApplication 测试一下。 

  1. datasource.tinyid.primary.driver-class-name=com.mysql.jdbc.Driver  
  2. datasource.tinyid.primary.url=jdbc:mysql://127.0.0.1:3306/xin-master?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8  
  3. datasource.tinyid.primary.username=junkang  
  4. datasource.tinyid.primary.password=junkang  
  5. datasource.tinyid.primary.testOnBorrow=false  
  6. datasource.tinyid.primary.maxActive=10  
  7. datasource.tinyid.secondary.driver-class-name=com.mysql.jdbc.Driver  
  8. datasource.tinyid.secondary.url=jdbc:mysql://localhost:3306/db2?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8  
  9. datasource.tinyid.secondary.username=root  
  10. datasource.tinyid.secondary.password=123456  
  11. datasource.tinyid.secondary.testOnBorrow=false  
  12. datasource.tinyid.secondary.maxActive=10 

1、Http方式

tinyid内部一共提供了四个http接口来获取ID和号段。 

  1. package com.xiaoju.uemc.tinyid.server.controller;  
  2. /**  
  3.  * @author du_imba  
  4.  */  
  5. @RestController  
  6. @RequestMapping("/id/")  
  7. public class IdContronller {   
  8.     private static final Logger logger = LoggerFactory.getLogger(IdContronller.class);  
  9.     @Autowired  
  10.     private IdGeneratorFactoryServer idGeneratorFactoryServer;  
  11.     @Autowired  
  12.     private SegmentIdService segmentIdService;  
  13.     @Autowired  
  14.     private TinyIdTokenService tinyIdTokenService;  
  15.     @Value("${batch.size.max}")  
  16.     private Integer batchSizeMax;  
  17.     @RequestMapping("nextId") 
  18.     public Response<List<Long>> nextId(String bizType, Integer batchSize, String token) {  
  19.         Response<List<Long>> response = new Response<>();  
  20.         try {  
  21.             IdGenerator idGenerator = idGeneratorFactoryServer.getIdGenerator(bizType);  
  22.             List<Long> ids = idGenerator.nextId(newBatchSize);  
  23.             response.setData(ids);  
  24.         } catch (Exception e) {  
  25.             response.setCode(ErrorCode.SYS_ERR.getCode());  
  26.             response.setMessage(e.getMessage());  
  27.             logger.error("nextId error", e);  
  28.         }  
  29.         return response; 
  30.     }  
  31.     @RequestMapping("nextIdSimple")  
  32.     public String nextIdSimple(String bizType, Integer batchSize, String token) {  
  33.         String response = "" 
  34.         try {  
  35.             IdGenerator idGenerator = idGeneratorFactoryServer.getIdGenerator(bizType);  
  36.             if (newBatchSize == 1) {  
  37.                 Long id = idGenerator.nextId();  
  38.                 response = id + "";  
  39.             } else {  
  40.                 List<Long> idList = idGenerator.nextId(newBatchSize);  
  41.                 StringBuilder sb = new StringBuilder();  
  42.                 for (Long id : idList) { 
  43.                     sb.append(id).append(",");  
  44.                 } 
  45.                  response = sb.deleteCharAt(sb.length() - 1).toString();  
  46.             }  
  47.         } catch (Exception e) {  
  48.             logger.error("nextIdSimple error", e); 
  49.         } 
  50.          return response;  
  51.     }  
  52.     @RequestMapping("nextSegmentId")  
  53.     public Response<SegmentId> nextSegmentId(String bizType, String token) {  
  54.         try {  
  55.             SegmentId segmentId = segmentIdService.getNextSegmentId(bizType);  
  56.             response.setData(segmentId);  
  57.         } catch (Exception e) {  
  58.             response.setCode(ErrorCode.SYS_ERR.getCode());  
  59.             response.setMessage(e.getMessage());  
  60.             logger.error("nextSegmentId error", e);  
  61.         }  
  62.         return response;  
  63.     }  
  64.     @RequestMapping("nextSegmentIdSimple")  
  65.     public String nextSegmentIdSimple(String bizType, String token) {  
  66.         String response = "" 
  67.         try {  
  68.             SegmentId segmentId = segmentIdService.getNextSegmentId(bizType); 
  69.              response = segmentId.getCurrentId() + "," + segmentId.getLoadingId() + "," + segmentId.getMaxId()  
  70.                     + "," + segmentId.getDelta() + "," + segmentId.getRemainder();  
  71.         } catch (Exception e) {  
  72.             logger.error("nextSegmentIdSimple error", e);  
  73.         }  
  74.         return response;  
  75.     }  

nextId、nextIdSimple都是获取下一个ID,nextSegmentIdSimple、getNextSegmentId是获取下一个可用号段。区别在于接口是否有返回状态。 

  1. nextId:  
  2. 'http://localhost:9999/tinyid/id/nextId?bizType=test&token=0f673adf80504e2eaa552f5d791b644c 
  3. response :  
  4.  
  5.     "data": [2],  
  6.     "code": 200,  
  7.     "message": ""  
  8.  
  9. nextId Simple:  
  10. 'http://localhost:9999/tinyid/id/nextIdSimple?bizType=test&token=0f673adf80504e2eaa552f5d791b644c 
  11. response: 3 

2、Tinyid-client客户端

如果不想通过http方式,Tinyid-client客户端也是一种不错的选择。

引用 tinyid-server包 

  1. <dependency>  
  2.     <groupId>com.xiaoju.uemc.tinyid</groupId>  
  3.     <artifactId>tinyid-client</artifactId>  
  4.     <version>${tinyid.version}</version>  
  5. </dependency> 

启动 tinyid-server项目打包后得到 tinyid-server-0.1.0-SNAPSHOT.jar ,设置版本 ${tinyid.version}为0.1.0-SNAPSHOT。

在我们的项目 application.properties 中配置 tinyid-server服务的请求地址 和 用户身份token 

  1. tinyid.server=127.0.0.1:9999  
  2. tinyid.token=0f673adf80504e2eaa552f5d791b644c``` 

在Java代码调用TinyId也很简单,只需要一行代码。 

  1. // 根据业务类型 获取单个ID  
  2. Long id = TinyId.nextId("test");  
  3. // 根据业务类型 批量获取10个ID  
  4. List<Long> ids = TinyId.nextId("test", 10);     

Tinyid整个项目的源码实现也是比较简单,像与数据库交互更直接用jdbcTemplate实现 

  1. @Override  
  2. public TinyIdInfo queryByBizType(String bizType) {  
  3.     String sql = "select id, biz_type, begin_id, max_id," +  
  4.             " step, delta, remainder, create_time, update_time, version" +  
  5.             " from tiny_id_info where biz_type = ?";  
  6.     List<TinyIdInfo> list = jdbcTemplate.query(sql, new Object[]{bizType}, new TinyIdInfoRowMapper());  
  7.     if(list == null || list.isEmpty()) {  
  8.         return null;  
  9.     }  
  10.     return list.get(0);  

总结

两种方式推荐使用Tinyid-client,这种方式ID为本地生成,号段长度(step)越长,支持的qps就越大,如果将号段设置足够大,则qps可达1000w+。而且tinyid-client 对 tinyid-server 访问变的低频,减轻了server端的压力。 

 

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/292969.html<

(0)
运维的头像运维
上一篇2025-05-20 09:49
下一篇 2025-05-20 09:50

相关推荐

  • 个人主题怎么制作?

    制作个人主题是一个将个人风格、兴趣或专业领域转化为视觉化或结构化内容的过程,无论是用于个人博客、作品集、社交媒体账号还是品牌形象,核心都是围绕“个人特色”展开,以下从定位、内容规划、视觉设计、技术实现四个维度,详细拆解制作个人主题的完整流程,明确主题定位:找到个人特色的核心主题定位是所有工作的起点,需要先回答……

    2025-11-20
    0
  • 社群营销管理关键是什么?

    社群营销的核心在于通过建立有温度、有价值、有归属感的社群,实现用户留存、转化和品牌传播,其管理需贯穿“目标定位-内容运营-用户互动-数据驱动-风险控制”全流程,以下从五个维度展开详细说明:明确社群定位与目标社群管理的首要任务是精准定位,需明确社群的核心价值(如行业交流、产品使用指导、兴趣分享等)、目标用户画像……

    2025-11-20
    0
  • 香港公司网站备案需要什么材料?

    香港公司进行网站备案是一个涉及多部门协调、流程相对严谨的过程,尤其需兼顾中国内地与香港两地的监管要求,由于香港公司注册地与中国内地不同,其网站若主要服务内地用户或使用内地服务器,需根据服务器位置、网站内容性质等,选择对应的备案路径(如工信部ICP备案或公安备案),以下从备案主体资格、流程步骤、材料准备、注意事项……

    2025-11-20
    0
  • 如何企业上云推广

    企业上云已成为数字化转型的核心战略,但推广过程中需结合行业特性、企业痛点与市场需求,构建系统性、多维度的推广体系,以下从市场定位、策略设计、执行落地及效果优化四个维度,详细拆解企业上云推广的实践路径,精准定位:明确目标企业与核心价值企业上云并非“一刀切”的方案,需先锁定目标客户群体,提炼差异化价值主张,客户分层……

    2025-11-20
    0
  • PS设计搜索框的实用技巧有哪些?

    在PS中设计一个美观且功能性的搜索框需要结合创意构思、视觉设计和用户体验考量,以下从设计思路、制作步骤、细节优化及交互预览等方面详细说明,帮助打造符合需求的搜索框,设计前的规划明确使用场景:根据网站或APP的整体风格确定搜索框的调性,例如极简风适合细线条和纯色,科技感适合渐变和发光效果,电商类则可能需要突出搜索……

    2025-11-20
    0

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注