大家好,又见面了,我是你们的朋友全栈君。
应用场景
全局流水号
- 区分前后台
- 包含日期,可以从流水号一眼看出日期
- 不需要显示在前台,可以在后台显示
- 唯一标识每一次请求
订单号 , 优惠券号码等电商业务相关
参考电商订单号设计的资料,自定义实现
数据库主键
- [单调]递增
- 可能考虑分库分表
- 使用 美团leaf
全局流水号
构成: 1/2/3-时间格式化-序号 1: auth 2: admin 3: api 例:
代码语言:javascript复制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
代码语言:javascript复制git clone git@github.com:Meituan-Dianping/Leaf.git
git checkout feature/spring-boot-starter
cd leaf
mvn clean install -Dmaven.test.skip=true
引入时需要注意mybatis依赖和druid依赖的冲突
代码语言:javascript复制<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=
建表语句
代码语言:javascript复制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')
测试
代码语言:javascript复制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"));
}
}
输出
代码语言:javascript复制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}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/148788.html原文链接:https://javaforall.cn