idworker java_Java IdWorker類代碼示例

本文整理匯總了Java中com.baomidou.mybatisplus.toolkit.IdWorker類的典型用法代碼示例。如果您正苦於以下問題:Java IdWorker類的具體用法?Java IdWorker怎麽用?Java IdWorker使用的例子?那麽恭喜您, 這裏精選的類代碼示例或許可以為您提供幫助。

IdWorker類屬於com.baomidou.mybatisplus.toolkit包,在下文中一共展示了IdWorker類的19個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Java代碼示例。

示例1: main

​點讚 3

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

/**

*

* 事務測試

*

*/

public static void main(String[] args) {

/*

* 加載配置文件

*/

InputStream in = TransactionalTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");

MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();

SqlSessionFactory sessionFactory = mf.build(in);

SqlSession sqlSession = sessionFactory.openSession();

/**

* 插入

*/

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

int rlt = userMapper.insert(new User(IdWorker.getId(), "1", 1, 1));

System.err.println("--------- insertInjector --------- " + rlt);

//session.commit();

sqlSession.rollback();

sqlSession.close();

}

開發者ID:Caratacus,項目名稱:mybatis-plus-mini,代碼行數:25,

示例2: main

​點讚 3

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

public static void main(String[] args) {

/*

* 加載配置文件

*/

InputStream in = NoXMLTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");

MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();

SqlSessionFactory sessionFactory = mf.build(in);

SqlSession sqlSession = sessionFactory.openSession();

/**

* 查詢是否有結果

*/

TestMapper testMapper = sqlSession.getMapper(TestMapper.class);

testMapper.insert(new Test(IdWorker.getId(), "Caratacus"));

List> list = testMapper.selectMaps(null);

List> list1 = testMapper.selectMapsPage(RowBounds.DEFAULT, null);

List> list2 = testMapper.selectMapsPage(new Page<>(1, 5), null);

System.out.println(list);

System.out.println(list1);

System.out.println(list2);

testMapper.delete(null);

}

開發者ID:Caratacus,項目名稱:mybatis-plus-mini,代碼行數:23,

示例3: test

​點讚 3

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

/**

*

* 事務測試

*

*/

@Test

public void test() {

SqlSession sqlSession = this.sqlSessionFactory().openSession();

/**

* 插入

*/

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

int rlt = userMapper.insert(new User(IdWorker.getId(), "1", 1, 1));

System.err.println("--------- insertInjector --------- " + rlt);

//session.commit();

sqlSession.rollback();

sqlSession.close();

}

開發者ID:baomidou,項目名稱:mybatis-plus,代碼行數:21,

示例4: populateKeys

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

/**

*

* 自定義元對象填充控製器

*

*

* @param metaObjectHandler 元數據填充處理器

* @param tableInfo 數據庫表反射信息

* @param ms MappedStatement

* @param parameterObject 插入數據庫對象

* @return Object

*/

protected static Object populateKeys(MetaObjectHandler metaObjectHandler, TableInfo tableInfo,

MappedStatement ms, Object parameterObject) {

if (null == tableInfo || StringUtils.isEmpty(tableInfo.getKeyProperty()) || null == tableInfo.getIdType()) {

/* 不處理 */

return parameterObject;

}

/* 自定義元對象填充控製器 */

MetaObject metaObject = ms.getConfiguration().newMetaObject(parameterObject);

if (ms.getSqlCommandType() == SqlCommandType.INSERT) {

if (IdType.ID_WORKER.equals(tableInfo.getIdType()) || IdType.UUID.equals(tableInfo.getIdType())) {

Object idValue = metaObject.getValue(tableInfo.getKeyProperty());

/* 自定義 ID */

if (StringUtils.checkValNull(idValue)) {

if (IdType.ID_WORKER.equals(tableInfo.getIdType())) {

metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.getId());

} else if (IdType.UUID.equals(tableInfo.getIdType())) {

metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.get32UUID());

}

}

}

// 插入填充

if (metaObjectHandler.openInsertFill()) {

metaObjectHandler.insertFill(metaObject);

}

} else if (ms.getSqlCommandType() == SqlCommandType.UPDATE && metaObjectHandler.openUpdateFill()) {

// 更新填充

metaObjectHandler.updateFill(metaObject);

}

return metaObject.getOriginalObject();

}

開發者ID:Caratacus,項目名稱:mybatis-plus-mini,代碼行數:42,

示例5: test

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

@Test

public void test() throws Exception {

double wucha = 0.05;

int count = 1000;

int wuchaNum = (int) (count * wucha);

int high = count + wuchaNum;

int low = count - wuchaNum;

System.err.println("共有" + count + "個數參與測試,誤差係數為" + wucha + "誤差值為" + wuchaNum);

ExecutorService executorService = Executors.newFixedThreadPool(20);

final List results = new ArrayList<>();

CompletionService cs = new ExecutorCompletionService<>(executorService);

for (int i = 1; i < count; i++) {

cs.submit(() -> {

Thread.sleep(RandomUtils.nextInt(1, 2000));

return IdWorker.getId();

});

}

for (int i = 0; i < count; i++) {

Future future = executorService.submit(IdWorker::getId);

results.add(future.get());

}

executorService.shutdown();

HashSet set = new HashSet<>(results);

// 判斷是否有重複

Assert.assertEquals(count, set.size());

int odd = 0;

int even = 0;

for (Long id : results) {

if (id % 2 != 0) {

odd++;

} else {

even++;

}

}

System.err.println("奇數:" + odd);

System.err.println("偶數:" + even);

Assert.assertTrue(odd >= low && odd <= high);

Assert.assertTrue(even >= low && even <= high);

}

開發者ID:Caratacus,項目名稱:mybatis-plus-mini,代碼行數:41,

示例6: testSqlInjector

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

public void testSqlInjector() {

Long id = IdWorker.getId();

int rlt = baseMapper.insert(new User(id, "abc", 18, 1));

System.err.println("插入ID:" + id + ", 執行結果:" + rlt);

rlt = baseMapper.deleteLogicById(id);

System.err.println("測試注入執行結果:" + rlt);

System.err.println("邏輯修改:" + baseMapper.selectById(id).toString());

}

開發者ID:Caratacus,項目名稱:mybatis-plus-mini,代碼行數:9,

示例7: populateKeys

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

/**

*

* 自定義元對象填充控製器

*

*

* @param metaObjectHandler 元數據填充處理器

* @param tableInfo 數據庫表反射信息

* @param ms MappedStatement

* @param parameterObject 插入數據庫對象

* @return Object

*/

protected static Object populateKeys(MetaObjectHandler metaObjectHandler, TableInfo tableInfo,

MappedStatement ms, Object parameterObject) {

if (null == tableInfo || StringUtils.isEmpty(tableInfo.getKeyProperty()) || null == tableInfo.getIdType()) {

/* 不處理 */

return parameterObject;

}

/* 自定義元對象填充控製器 */

MetaObject metaObject = ms.getConfiguration().newMetaObject(parameterObject);

if (ms.getSqlCommandType() == SqlCommandType.INSERT) {

if (tableInfo.getIdType().getKey() >= 2) {

Object idValue = metaObject.getValue(tableInfo.getKeyProperty());

/* 自定義 ID */

if (StringUtils.checkValNull(idValue)) {

if (tableInfo.getIdType() == IdType.ID_WORKER) {

metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.getId());

} else if (tableInfo.getIdType() == IdType.ID_WORKER_STR) {

metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.getIdStr());

} else if (tableInfo.getIdType() == IdType.UUID) {

metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.get32UUID());

}

}

}

// 插入填充

if (metaObjectHandler.openInsertFill()) {

metaObjectHandler.insertFill(metaObject);

}

} else if (ms.getSqlCommandType() == SqlCommandType.UPDATE && metaObjectHandler.openUpdateFill()) {

// 更新填充

metaObjectHandler.updateFill(metaObject);

}

return metaObject.getOriginalObject();

}

開發者ID:baomidou,項目名稱:mybatis-plus,代碼行數:44,

示例8: test

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

public void test() throws Exception {

int count = 1000;

System.err.println("共有" + count + "個數參與測試");

ExecutorService executorService = Executors.newFixedThreadPool(20);

final List results = new ArrayList<>();

CompletionService cs = new ExecutorCompletionService<>(executorService);

for (int i = 1; i < count; i++) {

cs.submit(new Callable() {

public Long call() throws Exception {

Thread.sleep(RandomUtils.nextInt(1, 2000));

return IdWorker.getId();

}

});

}

for (int i = 0; i < count; i++) {

Future future = executorService.submit(new Callable() {

@Override

public Long call() throws Exception {

return IdWorker.getId();

}

});

results.add(future.get());

}

executorService.shutdown();

HashSet set = new HashSet<>(results);

// 判斷是否有重複

Assert.assertEquals(count, set.size());

int odd = 0;

int even = 0;

for (Long id : results) {

if (id % 2 != 0) {

odd++;

} else {

even++;

}

}

System.err.println("奇數:" + odd);

System.err.println("偶數:" + even);

}

開發者ID:baomidou,項目名稱:mybatis-plus,代碼行數:41,

示例9: test2

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

public void test2() throws Exception {

// 隨機尾數

for (int i = 0; i < 1000; i++) {

Thread.sleep(10);

System.out.println(IdWorker.getId());

}

}

開發者ID:baomidou,項目名稱:mybatis-plus,代碼行數:8,

示例10: run

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

public void run() {

try {

long id = IdWorker.getId();

System.err.println(id);

} catch (Exception e) {

e.printStackTrace();

}

}

開發者ID:baomidou,項目名稱:mybatisplus-spring-mvc,代碼行數:9,

示例11: main

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

public static void main(String[] args) {

// 加載配置文件

InputStream in = TestMapper.class.getClassLoader().getResourceAsStream("mysql-config.xml");

MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();

SqlSessionFactory sqlSessionFactory = mf.build(in);

TableInfoHelper.initSqlSessionFactory(sqlSessionFactory);

sqlSessionFactory.openSession(false);

// 保存一條記錄

Test t1 = new Test();

t1.setType("test10");

boolean rlt = t1.insert();

print(" ar save=" + rlt + ", id=" + t1.getId());

// 根據ID更新

t1.setType("t1023");

rlt = t1.updateById();

print(" ar updateById:" + rlt);

// 更新 SQL

Test t11 = new Test();

t11.setType("123");

rlt = t11.update("id={0}", t1.getId());

print("update sql=" + rlt);

// 查詢 SQL

Test t10 = t1.selectOne("id={0}", t1.getId());

print("selectOne=" + t10.getType());

// 插入OR更新

t1.setType("t1021");

rlt = t1.insertOrUpdate();

print(" ar saveOrUpdate:" + rlt);

// 根據ID查詢

Test t2 = t1.selectById();

print(" t2 = " + t2.toString());

t2.setId(IdWorker.getId());

t2.insert();

// 查詢所有

List tl = t2.selectAll();

for (Test t : tl) {

print("selectAll=" + t.toString());

}

// 查詢總記錄數

print(" count=" + t2.selectCount(null));

// 翻頁查詢

Page page = new Page<>(0, 10);

page = t2.selectPage(page, null);

print(page.toString());

// 根據ID刪除

rlt = t2.deleteById();

print("deleteById=" + rlt + ", id=" + t2.getId());

// 根據ID查詢

Test t20 = t2.selectById();

print("t2 刪除後是否存在?" + (null != t20));

// 刪除 SQL

rlt = t2.delete("type={0}", "t1021");

System.err.println("delete sql=" + rlt);

}

開發者ID:Caratacus,項目名稱:mybatis-plus-mini,代碼行數:66,

示例12: main

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

public static void main(String[] args) {

// 加載配置文件

InputStream in = UserMapperTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");

MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();

mf.setGlobalConfig(new GlobalConfiguration(new MySqlInjector()));

SqlSessionFactory sessionFactory = mf.build(in);

SqlSession session = sessionFactory.openSession();

UserMapper userMapper = session.getMapper(UserMapper.class);

RoleMapper roleMapper = session.getMapper(RoleMapper.class);

/**

* sjy 測試@TableField的el屬性, 級聯resultMap

*/

Role role = new Role();

role.setId(IdWorker.getId());

role.setName("admin");

int rlt = roleMapper.insert(role);

System.err.println("--------- insert role --------- " + rlt);

PhoneNumber phone = new PhoneNumber("81", "0576", "82453832");

User userA = new User();

userA.setId(IdWorker.getId());

userA.setName("junyu_shi");

userA.setAge(15);

userA.setTestType(1);

userA.setRole(role);

userA.setPhone(phone);

rlt = userMapper.insert(userA);

System.err.println("--------- insert user --------- " + rlt);

User whereUser = userMapper.selectOne(userA);

System.err.println("--------- select user --------- " + whereUser.toString());

// 如果不使用el表達式, User類中就同時需要roleId用於對應User表中的字段,

// 和Role屬性用於保存resultmap的級聯查詢. 在插入時, 就需要寫user.setRoleId(), 然後updateUser.

role = new Role();

role.setId(IdWorker.getId());

role.setName("root");

roleMapper.insert(role);

userA.setRole(role);

userMapper.updateById(userA);

System.err.println("--------- upadte user's role --------- " + rlt);

whereUser = userMapper.selectOne(userA);

System.err.println("--------- select user --------- " + whereUser.toString());

userMapper.delete(new EntityWrapper<>(userA));

System.err.println("--------- delete user --------- " + rlt);

}

開發者ID:Caratacus,項目名稱:mybatis-plus-mini,代碼行數:53,

示例13: pushOrder

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

/**

* 下單

* @param mch_id 商戶號

* @param appId APPID

* @param partnerKey 安全密鑰

* @param trade_type 交易類型(APP/MWEB)

* @param out_trade_no 商戶訂單號

* @param body 商品描述

* @param detail 商品詳細描述

* @param amount 交易金額

* @param scene_info 場景信息

* @param ip 客戶端IP

* @param callBack 回調地址

* @return 支付參數

*/

public static Map pushOrder(String mch_id, String appId, String partnerKey, String trade_type,

String out_trade_no, String body, String detail, BigDecimal amount, String scene_info, String ip,

String callBack, String openId) {

String total_fee = amount.multiply(new BigDecimal("100")).setScale(0).toString();

Map params = WxPayment.buildUnifiedOrderParasMap(appId, null, mch_id, null, null, body, detail,

null, out_trade_no, total_fee, ip, callBack, trade_type, partnerKey, null, scene_info, openId);

logger.info("WeChart order parameter : " + JSON.toJSONString(params));

String result = WxPay.pushOrder(params);

logger.info("WeChart order result : " + result);

Map resultMap = WxPayment.xmlToMap(result);

String return_code = resultMap.get("return_code");

if (WxPayment.codeIsOK(return_code)) {

String result_code = resultMap.get("result_code");

if (WxPayment.codeIsOK(result_code)) {

String sign = resultMap.get("sign");

String mySign = WxPayment.createSign(resultMap, partnerKey);

if (mySign.equals(sign)) {

String prepay_id = resultMap.get("prepay_id");

String mweb_url = resultMap.get("mweb_url");

resultMap.clear();

resultMap.put("prepayid", prepay_id);

if ("APP".equals(trade_type)) {

resultMap.put("partnerId", mch_id);

}

if (DataUtil.isNotEmpty(mweb_url)) {

resultMap.put("mwebUrl", mweb_url);

} else {

resultMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));

resultMap.put("noncestr", IdWorker.get32UUID());

sign = WxPayment.buildOrderPaySign(appId, mch_id, prepay_id, trade_type,

resultMap.get("timestamp"), resultMap.get("noncestr"), partnerKey);

resultMap.put("sign", sign);

}

return resultMap;

} else {

throw new RuntimeException("微信返回數據異常.");

}

} else {

throw new RuntimeException(resultMap.get("err_code_des"));

}

} else {

throw new RuntimeException(resultMap.get("return_msg"));

}

}

開發者ID:iBase4J,項目名稱:iBase4J-Common,代碼行數:60,

示例14: test1

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

public void test1() throws Exception {

// 毫秒內並發

for (int i = 0; i < 1000; i++) {

System.out.println(IdWorker.getId());

}

}

開發者ID:baomidou,項目名稱:mybatis-plus,代碼行數:7,

示例15: test

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

@org.junit.Test

public void test() {

TableInfoHelper.initSqlSessionFactory(this.sqlSessionFactory());

// 保存一條記錄

Test t1 = new Test();

t1.setType("test10");

boolean rlt = t1.insert();

print(" ar save=" + rlt + ", id=" + t1.getId());

// 根據ID更新

t1.setType("t1001");

rlt = t1.updateAllColumnById();

print(" ar updateAllColumnById:" + rlt);

t1.setType("t1023");

rlt = t1.updateById();

print(" ar updateById:" + rlt);

// 更新 SQL

Test t11 = new Test();

t11.setType("123");

rlt = t11.update("id={0}", t1.getId());

print("update sql=" + rlt);

// 查詢 SQL

Test t10 = t1.selectOne("id={0}", t1.getId());

print("selectOne=" + t10.getType());

// 插入OR更新

t1.setType("t1021");

rlt = t1.insertOrUpdate();

print(" ar saveOrUpdate:" + rlt);

// 根據ID查詢

Test t2 = t1.selectById();

print(" t2 = " + t2.toString());

t2.setId(IdWorker.getId());

t2.insert();

// 查詢所有

List tl = t2.selectAll();

for (Test t : tl) {

print("selectAll=" + t.toString());

}

// 查詢總記錄數

print(" count=" + t2.selectCount(null));

// 翻頁查詢

Page page = new Page<>(0, 10);

page = t2.selectPage(page, null);

print(page.toString());

// 根據ID刪除

rlt = t2.deleteById();

print("deleteById=" + rlt + ", id=" + t2.getId());

// 執行 SQL 查詢總數

List> ul = t2.sql().selectList(new SQL() {

{

SELECT("*");

FROM("test");

WHERE("type='t1021'");

}

}.toString());

System.err.println("selectList SQL:");

for (Map map : ul) {

System.err.println(map);

}

// 根據ID查詢

Test t20 = t2.selectById();

print("t2 刪除後是否存在?" + (null != t20));

// 刪除 SQL

rlt = t2.delete("type={0}", "t1021");

System.err.println("delete sql=" + rlt);

}

開發者ID:baomidou,項目名稱:mybatis-plus,代碼行數:79,

示例16: urpTest

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

@Test

public void urpTest() {

// 加載配置文件

SqlSession session = this.sqlSessionFactory().openSession();

UserMapper userMapper = session.getMapper(UserMapper.class);

RoleMapper roleMapper = session.getMapper(RoleMapper.class);

/**

* sjy 測試@TableField的el屬性, 級聯resultMap

*/

Role role = new Role();

role.setId(IdWorker.getId());

role.setName("admin");

int rlt = roleMapper.insert(role);

System.err.println("--------- insert role --------- " + rlt);

PhoneNumber phone = new PhoneNumber("81", "0576", "82453832");

User userA = new User();

userA.setId(IdWorker.getId());

userA.setName("junyu_shi");

userA.setAge(15);

userA.setTestType(1);

userA.setRole(role);

userA.setPhone(phone);

rlt = userMapper.insert(userA);

System.err.println("--------- insert user --------- " + rlt);

User whereUser = userMapper.selectOne(userA);

System.err.println("--------- select user --------- " + whereUser.toString());

// 如果不使用el表達式, User類中就同時需要roleId用於對應User表中的字段,

// 和Role屬性用於保存resultmap的級聯查詢. 在插入時, 就需要寫user.setRoleId(), 然後updateUser.

role = new Role();

role.setId(IdWorker.getId());

role.setName("root");

roleMapper.insert(role);

userA.setRole(role);

userMapper.updateById(userA);

System.err.println("--------- upadte user's role --------- " + rlt);

whereUser = userMapper.selectOne(userA);

System.err.println("--------- select user --------- " + whereUser.toString());

userMapper.delete(new EntityWrapper<>(userA));

System.err.println("--------- delete user --------- " + rlt);

}

開發者ID:baomidou,項目名稱:mybatis-plus,代碼行數:50,

示例17: toMessage

​點讚 2

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

@Override

public Message toMessage(Object o, Session session) throws JMSException, MessageConversionException {

return session.createTextMessage(JSON.toJSONString(new JmsMsg().setData(o).setMsgId(IdWorker.getId()), SerializerFeature.WriteClassName));

}

開發者ID:jayqqaa12,項目名稱:jbase,代碼行數:5,

示例18: buildSignAfterParasMap

​點讚 1

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

/**

* 構建簽名之後的參數

*

* @param params

* @param paternerKey

* @return Map

*/

public static Map buildSignAfterParasMap(Map params, String paternerKey) {

params.put("nonce_str", IdWorker.get32UUID());

String sign = WxPayment.createSign(params, paternerKey);

params.put("sign", sign);

return params;

}

開發者ID:iBase4J,項目名稱:iBase4J-Common,代碼行數:14,

示例19: buildSignAfterParasMap

​點讚 1

import com.baomidou.mybatisplus.toolkit.IdWorker; //導入依賴的package包/類

/**

* 構建簽名之後的參數

*

* @param params

* @param paternerKey

* @return Map

*/

public static Map buildSignAfterParasMap(Map params, String paternerKey) {

params.put("nonce_str", IdWorker.get32UUID());

String sign = WxPayment.createSign(params, paternerKey);

params.put("sign", sign);

return params;

}

開發者ID:guokezheng,項目名稱:automat,代碼行數:14,

注:本文中的com.baomidou.mybatisplus.toolkit.IdWorker類示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
高并发分布式系统中生成全局唯一Id汇总 数据在分片时,典型的是分库分表,就有一个全局ID生成的问题。 单纯的生成全局ID并不是什么难题,但是生成的ID通常要满足分片的一些要求: 1 不能有单点故障。 2 以时间为序,或者ID里包含时间。这样一是可以少一个索引,二是冷热数据容易分离。 3 可以控制ShardingId。比如某一个用户的文章要放在同一个分片内,这样查询效率高,修改也容易。 4 不要太长,最好64bit。使用long比较好操作,如果是96bit,那就要各种移位相当的不方便,还有可能有些组件不能支持这么大的ID。 一 twitter twitter在把存储系统从MySQL迁移到Cassandra的过程中由于Cassandra没有顺序ID生成机制,于是自己开发了一套全局唯一ID生成服务:Snowflake。 1 41位的时间序列(精确到毫秒,41位的长度可以使用69年) 2 10位的机器标识(10位的长度最多支持部署1024个节点) 3 12位的计数顺序号(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) 最高位是符号位,始终为0。 优点:高性能,低延迟;独立的应用;按时间有序。 缺点:需要独立的开发和部署。 原理 java 实现代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 public class IdWorker { private final long workerId; private final static long twepoch = 1288834974657L; private long sequence = 0L; private final static long workerIdBits = 4L; public final static long maxWorkerId = -1L ^ -1L << workerIdBits; private final static long sequenceBits = 10L; private final static long workerIdShift = sequenceBits; private final static long timestampLeftShift = sequenceBits + workerIdBits; public final static long sequenceMask = -1L ^ -1L < this.maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format( "worker Id can't be greater than %d or less than 0", this.maxWorkerId)); } this.workerId = workerId; } public synchronized long nextId() { long timestamp = this.timeGen(); if (this.lastTimestamp == timestamp) { this.sequence = (this.sequence + 1) & this.sequenceMask; if (this.sequence == 0) { System.out.println("###########" + sequenceMask); timestamp = this.tilNextMillis(this.lastTimestamp); } } else { this.sequence = 0; } if (timestamp < this.lastTimestamp) { try { throw new Exception( String.format( "Clock moved backwards. Refusing to generate id for %d milliseconds", this.lastTimestamp - timestamp)); } catch (Exception e) { e.printStackTrace(); } } this.lastTimestamp = timestamp; long nextId = ((timestamp - twepoch << timestampLeftShift)) | (this.workerId << this.workerIdShift) | (this.sequence); System.out.println("timestamp:" + timestamp + ",timestampLeftShift:" + timestampLeftShift + ",nextId:" + nextId + ",workerId:" + workerId + ",sequence:" + sequence); return nextId; } private long tilNextMillis(final long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; } private long timeGen() { return System.currentTimeMillis(); } public static void main(String[] args){ IdWorker worker2 = new IdWorker(2); System.out.println(worker2.nextId()); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值