id 生成器

应用场景

  1. 全局流水号
  1. 区分前后台
  2. 包含日期,可以从流水号一眼看出日期
  3. 不需要显示在前台,可以在后台显示
  4. 唯一标识每一次请求
  1. 订单号 , 优惠券号码等电商业务相关

参考电商订单号设计的资料,自定义实现

  1. 数据库主键
  1. [单调]递增
  2. 可能考虑分库分表
  3. 使用 美团leaf

全局流水号

构成: 1/2/3-时间格式化-序号
1: auth
2: admin
3: api
例:

2-2020-10-28-22:58:58-3

代码参考

https://gitee.com/sanren2016/shop-boot/tree/847b1c1d9037d8156d91c588561806c39edee63e/

效果

在这里插入图片描述

实现思路

使用全局拦截器+ThreadLocal,在preHandle中获取流水号,流水号获取代码:
com.laolang.shop.common.data.mvc.trace.TraceComponent

美团 Leaf

参考: https://github.com/Meituan-Dianping/Leaf/blob/master/README_CN.md

git clone [email protected]:Meituan-Dianping/Leaf.git
git checkout feature/spring-boot-starter
cd leaf
mvn clean install -Dmaven.test.skip=true 

引入时需要注意mybatis依赖和druid依赖的冲突

<dependency>
    <artifactId>leaf-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>druid</artifactId>
            <groupId>com.alibaba</groupId>
        </exclusion>
        <exclusion>
            <artifactId>mybatis</artifactId>
            <groupId>org.mybatis</groupId>
        </exclusion>
    </exclusions>
    <groupId>com.sankuai.inf.leaf</groupId>
    <version>1.0.1-RELEASE</version>
</dependency>

配置文件: leaf.properties

leaf.name=shop-boot-leaf
leaf.segment.enable=true
leaf.segment.url=jdbc:mysql://192.168.1.110:3306/shop_boot?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
leaf.segment.username=shopboot
leaf.segment.password=shopboot

leaf.snowflake.enable=false
#leaf.snowflake.address=
#leaf.snowflake.port=

建表语句

CREATE TABLE `leaf_alloc` (
  `biz_tag` varchar(128)  NOT NULL DEFAULT '',
  `max_id` bigint(20) NOT NULL DEFAULT '1',
  `step` int(11) NOT NULL,
  `description` varchar(256)  DEFAULT NULL,
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`biz_tag`)
) ENGINE=InnoDB;

insert into leaf_alloc(biz_tag, max_id, step, description) values('leaf-segment-test', 1, 2000, 'Test leaf Segment Mode Get Id')

测试

package com.laolang.shop;

import com.sankuai.inf.leaf.service.SegmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.annotations.Test;

public class ComponentTest extends BaseComponentTest {
    
    

    @Autowired
    private SegmentService segmentService;

    @Test
    public void componentTest() {
    
    
        System.out.println(segmentService.getId("leaf-segment-test"));
        System.out.println(segmentService.getId("leaf-segment-test"));
        System.out.println(segmentService.getId("leaf-segment-test"));
        System.out.println(segmentService.getId("leaf-segment-test"));
        System.out.println(segmentService.getId("leaf-segment-test"));
    }
}

输出

Result{id=1, status=SUCCESS}
Result{id=2, status=SUCCESS}
Result{id=3, status=SUCCESS}
Result{id=4, status=SUCCESS}
Result{id=5, status=SUCCESS}

猜你喜欢

转载自blog.csdn.net/m0_46533764/article/details/109269517