生成订单
創建訂單接口
可以通過頁面看到接口信息:
-
請求方式:POST
-
請求路徑:/order
-
請求參數:包含訂單、訂單詳情等數據的json對象。
-
返回結果:訂單編號
點擊Try It Out來測試:
輸入數據:
{"totalPay": 236800,"postFee": 0,"paymentType": 2,"actualPay": 236800,"buyerMessage": null,"buyerNick": "huge","orderDetails": [{"skuId": 3893493,"num": 1,"title": "蘋果(Apple)iPhone 6 (A1586) 16GB 金色 移動聯通電信4G手機3","price": 236800,"ownSpec": "{\"機身顏色\":\"鉆雕藍\",\"內存\":\"4GB\",\"機身存儲\":\"64GB\"}","image": "http://image.learn.com/images/9/4/1524297342728.jpg"}],"receiver": "鋒哥","receiverMobile": "15800000000","receiverState": "上海","receiverCity": "上海","receiverDistrict": "浦東新簽","receiverAddress": "航頭鎮航頭路18號傳智播客3號樓","receiverZip": "210000","invoiceType": 0,"sourceType":2 }然后點擊execute:
結果:
下單需要登錄,通過登錄生成token:
把token的值手動加入到瀏覽器的cookie中:
添加成功,響應訂單編號。但是和數據庫保存的訂單編號不太一樣(后幾位不一樣,瀏覽器展示長整型會出現精度損失)
?
生成ID的方式
訂單id的特殊性
訂單數據非常龐大,將來一定會做分庫分表。那么這種情況下, 要保證id的唯一,就不能靠數據庫自增,而是自己來實現算法,生成唯一id。
?
雪花算法
這里的訂單id是通過一個工具類生成的:
而工具類所采用的生成id算法,是由Twitter公司開源的snowflake(雪花)算法。
簡單原理
雪花算法會生成一個64位的二進制數據,為一個Long型。(轉換成字符串后長度最多19) ,其基本結構:
第一位:為未使用
第二部分:41位為毫秒級時間(41位的長度可以使用69年)
第三部分:5位datacenterId和5位workerId(10位的長度最多支持部署1024個節點)
第四部分:最后12位是毫秒內的計數(12位的計數順序號支持每個節點每毫秒產生4096個ID序號)
snowflake生成的ID整體上按照時間自增排序,并且整個分布式系統內不會產生ID碰撞(由datacenter和workerId作區分),并且效率較高。經測試snowflake每秒能夠產生26萬個ID。
配置
為了保證不重復,我們給每個部署的節點都配置機器id:
learn:worker:workerId: 1datacenterId: 1加載屬性:
@ConfigurationProperties(prefix = "learn.worker") public class IdWorkerProperties {private long workerId;// 當前機器idprivate long datacenterId;// 序列號public long getWorkerId() {return workerId;}public void setWorkerId(long workerId) {this.workerId = workerId;}public long getDatacenterId() {return datacenterId;}public void setDatacenterId(long datacenterId) {this.datacenterId = datacenterId;} }編寫配置類:
@Configuration @EnableConfigurationProperties(IdWorkerProperties.class) public class IdWorkerConfig {@Beanpublic IdWorker idWorker(IdWorkerProperties prop) {return new IdWorker(prop.getWorkerId(), prop.getDatacenterId());} }使用:
?
總結