当前位置:   article > 正文

分布式ID选型对比(4)

分布式ID选型对比(4)

百度UID generator

一, 创建表: worker_node(在项目启动时初始化生成workId)

  1. CREATE TABLE `worker_node` (
  2. `ID` bigint NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
  3. `HOST_NAME` varchar(64) NOT NULL COMMENT 'host name',
  4. `PORT` varchar(64) NOT NULL COMMENT 'port',
  5. `TYPE` int NOT NULL COMMENT 'node type: ACTUAL or CONTAINER',
  6. `LAUNCH_DATE` date NOT NULL COMMENT 'launch date',
  7. `MODIFIED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'modified time',
  8. `CREATED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'created time',
  9. PRIMARY KEY (`ID`)
  10. ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb3 COMMENT='DB WorkerID Assigner for UID Generator';

二, 创建Model及Exmple、Dao

Model: WorkerNode

  1. package org.com.spi.model;
  2. import java.util.Date;
  3. public class WorkerNode {
  4. private Long id;
  5. private String hostName;
  6. private String port;
  7. private Integer type;
  8. private Date launchDate;
  9. private Date modified;
  10. private Date created;
  11. public Long getId() {
  12. return id;
  13. }
  14. public void setId(Long id) {
  15. this.id = id;
  16. }
  17. public String getHostName() {
  18. return hostName;
  19. }
  20. public void setHostName(String hostName) {
  21. this.hostName = hostName == null ? null : hostName.trim();
  22. }
  23. public String getPort() {
  24. return port;
  25. }
  26. public void setPort(String port) {
  27. this.port = port == null ? null : port.trim();
  28. }
  29. public Integer getType() {
  30. return type;
  31. }
  32. public void setType(Integer type) {
  33. this.type = type;
  34. }
  35. public Date getLaunchDate() {
  36. return launchDate;
  37. }
  38. public void setLaunchDate(Date launchDate) {
  39. this.launchDate = launchDate;
  40. }
  41. public Date getModified() {
  42. return modified;
  43. }
  44. public void setModified(Date modified) {
  45. this.modified = modified;
  46. }
  47. public Date getCreated() {
  48. return created;
  49. }
  50. public void setCreated(Date created) {
  51. this.created = created;
  52. }
  53. }

Example: WorkerNodeExample

  1. package org.com.spi.model;
  2. import java.util.ArrayList;
  3. import java.util.Date;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. public class WorkerNodeExample {
  7. protected String orderByClause;
  8. protected boolean distinct;
  9. protected List<Criteria> oredCriteria;
  10. public WorkerNodeExample() {
  11. oredCriteria = new ArrayList<Criteria>();
  12. }
  13. public void setOrderByClause(String orderByClause) {
  14. this.orderByClause = orderByClause;
  15. }
  16. public String getOrderByClause() {
  17. return orderByClause;
  18. }
  19. public void setDistinct(boolean distinct) {
  20. this.distinct = distinct;
  21. }
  22. public boolean isDistinct() {
  23. return distinct;
  24. }
  25. public List<Criteria> getOredCriteria() {
  26. return oredCriteria;
  27. }
  28. public void or(Criteria criteria) {
  29. oredCriteria.add(criteria);
  30. }
  31. public Criteria or() {
  32. Criteria criteria = createCriteriaInternal();
  33. oredCriteria.add(criteria);
  34. return criteria;
  35. }
  36. public Criteria createCriteria() {
  37. Criteria criteria = createCriteriaInternal();
  38. if (oredCriteria.size() == 0) {
  39. oredCriteria.add(criteria);
  40. }
  41. return criteria;
  42. }
  43. protected Criteria createCriteriaInternal() {
  44. Criteria criteria = new Criteria();
  45. return criteria;
  46. }
  47. public void clear() {
  48. oredCriteria.clear();
  49. orderByClause = null;
  50. distinct = false;
  51. }
  52. protected abstract static class GeneratedCriteria {
  53. protected List<Criterion> criteria;
  54. protected GeneratedCriteria() {
  55. super();
  56. criteria = new ArrayList<Criterion>();
  57. }
  58. public boolean isValid() {
  59. return criteria.size() > 0;
  60. }
  61. public List<Criterion> getAllCriteria() {
  62. return criteria;
  63. }
  64. public List<Criterion> getCriteria() {
  65. return criteria;
  66. }
  67. protected void addCriterion(String condition) {
  68. if (condition == null) {
  69. throw new RuntimeException("Value for condition cannot be null");
  70. }
  71. criteria.add(new Criterion(condition));
  72. }
  73. protected void addCriterion(String condition, Object value, String property) {
  74. if (value == null) {
  75. throw new RuntimeException("Value for " + property + " cannot be null");
  76. }
  77. criteria.add(new Criterion(condition, value));
  78. }
  79. protected void addCriterion(String condition, Object value1, Object value2, String property) {
  80. if (value1 == null || value2 == null) {
  81. throw new RuntimeException("Between values for " + property + " cannot be null");
  82. }
  83. criteria.add(new Criterion(condition, value1, value2));
  84. }
  85. protected void addCriterionForJDBCDate(String condition, Date value, String property) {
  86. if (value == null) {
  87. throw new RuntimeException("Value for " + property + " cannot be null");
  88. }
  89. addCriterion(condition, new java.sql.Date(value.getTime()), property);
  90. }
  91. protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
  92. if (values == null || values.size() == 0) {
  93. throw new RuntimeException("Value list for " + property + " cannot be null or empty");
  94. }
  95. List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
  96. Iterator<Date> iter = values.iterator();
  97. while (iter.hasNext()) {
  98. dateList.add(new java.sql.Date(iter.next().getTime()));
  99. }
  100. addCriterion(condition, dateList, property);
  101. }
  102. protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
  103. if (value1 == null || value2 == null) {
  104. throw new RuntimeException("Between values for " + property + " cannot be null");
  105. }
  106. addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
  107. }
  108. public Criteria andIdIsNull() {
  109. addCriterion("ID is null");
  110. return (Criteria) this;
  111. }
  112. public Criteria andIdIsNotNull() {
  113. addCriterion("ID is not null");
  114. return (Criteria) this;
  115. }
  116. public Criteria andIdEqualTo(Long value) {
  117. addCriterion("ID =", value, "id");
  118. return (Criteria) this;
  119. }
  120. public Criteria andIdNotEqualTo(Long value) {
  121. addCriterion("ID <>", value, "id");
  122. return (Criteria) this;
  123. }
  124. public Criteria andIdGreaterThan(Long value) {
  125. addCriterion("ID >", value, "id");
  126. return (Criteria) this;
  127. }
  128. public Criteria andIdGreaterThanOrEqualTo(Long value) {
  129. addCriterion("ID >=", value, "id");
  130. return (Criteria) this;
  131. }
  132. public Criteria andIdLessThan(Long value) {
  133. addCriterion("ID <", value, "id");
  134. return (Criteria) this;
  135. }
  136. public Criteria andIdLessThanOrEqualTo(Long value) {
  137. addCriterion("ID <=", value, "id");
  138. return (Criteria) this;
  139. }
  140. public Criteria andIdIn(List<Long> values) {
  141. addCriterion("ID in", values, "id");
  142. return (Criteria) this;
  143. }
  144. public Criteria andIdNotIn(List<Long> values) {
  145. addCriterion("ID not in", values, "id");
  146. return (Criteria) this;
  147. }
  148. public Criteria andIdBetween(Long value1, Long value2) {
  149. addCriterion("ID between", value1, value2, "id");
  150. return (Criteria) this;
  151. }
  152. public Criteria andIdNotBetween(Long value1, Long value2) {
  153. addCriterion("ID not between", value1, value2, "id");
  154. return (Criteria) this;
  155. }
  156. public Criteria andHostNameIsNull() {
  157. addCriterion("HOST_NAME is null");
  158. return (Criteria) this;
  159. }
  160. public Criteria andHostNameIsNotNull() {
  161. addCriterion("HOST_NAME is not null");
  162. return (Criteria) this;
  163. }
  164. public Criteria andHostNameEqualTo(String value) {
  165. addCriterion("HOST_NAME =", value, "hostName");
  166. return (Criteria) this;
  167. }
  168. public Criteria andHostNameNotEqualTo(String value) {
  169. addCriterion("HOST_NAME <>", value, "hostName");
  170. return (Criteria) this;
  171. }
  172. public Criteria andHostNameGreaterThan(String value) {
  173. addCriterion("HOST_NAME >", value, "hostName");
  174. return (Criteria) this;
  175. }
  176. public Criteria andHostNameGreaterThanOrEqualTo(String value) {
  177. addCriterion("HOST_NAME >=", value, "hostName");
  178. return (Criteria) this;
  179. }
  180. public Criteria andHostNameLessThan(String value) {
  181. addCriterion("HOST_NAME <", value, "hostName");
  182. return (Criteria) this;
  183. }
  184. public Criteria andHostNameLessThanOrEqualTo(String value) {
  185. addCriterion("HOST_NAME <=", value, "hostName");
  186. return (Criteria) this;
  187. }
  188. public Criteria andHostNameLike(String value) {
  189. addCriterion("HOST_NAME like", value, "hostName");
  190. return (Criteria) this;
  191. }
  192. public Criteria andHostNameNotLike(String value) {
  193. addCriterion("HOST_NAME not like", value, "hostName");
  194. return (Criteria) this;
  195. }
  196. public Criteria andHostNameIn(List<String> values) {
  197. addCriterion("HOST_NAME in", values, "hostName");
  198. return (Criteria) this;
  199. }
  200. public Criteria andHostNameNotIn(List<String> values) {
  201. addCriterion("HOST_NAME not in", values, "hostName");
  202. return (Criteria) this;
  203. }
  204. public Criteria andHostNameBetween(String value1, String value2) {
  205. addCriterion("HOST_NAME between", value1, value2, "hostName");
  206. return (Criteria) this;
  207. }
  208. public Criteria andHostNameNotBetween(String value1, String value2) {
  209. addCriterion("HOST_NAME not between", value1, value2, "hostName");
  210. return (Criteria) this;
  211. }
  212. public Criteria andPortIsNull() {
  213. addCriterion("PORT is null");
  214. return (Criteria) this;
  215. }
  216. public Criteria andPortIsNotNull() {
  217. addCriterion("PORT is not null");
  218. return (Criteria) this;
  219. }
  220. public Criteria andPortEqualTo(String value) {
  221. addCriterion("PORT =", value, "port");
  222. return (Criteria) this;
  223. }
  224. public Criteria andPortNotEqualTo(String value) {
  225. addCriterion("PORT <>", value, "port");
  226. return (Criteria) this;
  227. }
  228. public Criteria andPortGreaterThan(String value) {
  229. addCriterion("PORT >", value, "port");
  230. return (Criteria) this;
  231. }
  232. public Criteria andPortGreaterThanOrEqualTo(String value) {
  233. addCriterion("PORT >=", value, "port");
  234. return (Criteria) this;
  235. }
  236. public Criteria andPortLessThan(String value) {
  237. addCriterion("PORT <", value, "port");
  238. return (Criteria) this;
  239. }
  240. public Criteria andPortLessThanOrEqualTo(String value) {
  241. addCriterion("PORT <=", value, "port");
  242. return (Criteria) this;
  243. }
  244. public Criteria andPortLike(String value) {
  245. addCriterion("PORT like", value, "port");
  246. return (Criteria) this;
  247. }
  248. public Criteria andPortNotLike(String value) {
  249. addCriterion("PORT not like", value, "port");
  250. return (Criteria) this;
  251. }
  252. public Criteria andPortIn(List<String> values) {
  253. addCriterion("PORT in", values, "port");
  254. return (Criteria) this;
  255. }
  256. public Criteria andPortNotIn(List<String> values) {
  257. addCriterion("PORT not in", values, "port");
  258. return (Criteria) this;
  259. }
  260. public Criteria andPortBetween(String value1, String value2) {
  261. addCriterion("PORT between", value1, value2, "port");
  262. return (Criteria) this;
  263. }
  264. public Criteria andPortNotBetween(String value1, String value2) {
  265. addCriterion("PORT not between", value1, value2, "port");
  266. return (Criteria) this;
  267. }
  268. public Criteria andTypeIsNull() {
  269. addCriterion("TYPE is null");
  270. return (Criteria) this;
  271. }
  272. public Criteria andTypeIsNotNull() {
  273. addCriterion("TYPE is not null");
  274. return (Criteria) this;
  275. }
  276. public Criteria andTypeEqualTo(Integer value) {
  277. addCriterion("TYPE =", value, "type");
  278. return (Criteria) this;
  279. }
  280. public Criteria andTypeNotEqualTo(Integer value) {
  281. addCriterion("TYPE <>", value, "type");
  282. return (Criteria) this;
  283. }
  284. public Criteria andTypeGreaterThan(Integer value) {
  285. addCriterion("TYPE >", value, "type");
  286. return (Criteria) this;
  287. }
  288. public Criteria andTypeGreaterThanOrEqualTo(Integer value) {
  289. addCriterion("TYPE >=", value, "type");
  290. return (Criteria) this;
  291. }
  292. public Criteria andTypeLessThan(Integer value) {
  293. addCriterion("TYPE <", value, "type");
  294. return (Criteria) this;
  295. }
  296. public Criteria andTypeLessThanOrEqualTo(Integer value) {
  297. addCriterion("TYPE <=", value, "type");
  298. return (Criteria) this;
  299. }
  300. public Criteria andTypeIn(List<Integer> values) {
  301. addCriterion("TYPE in", values, "type");
  302. return (Criteria) this;
  303. }
  304. public Criteria andTypeNotIn(List<Integer> values) {
  305. addCriterion("TYPE not in", values, "type");
  306. return (Criteria) this;
  307. }
  308. public Criteria andTypeBetween(Integer value1, Integer value2) {
  309. addCriterion("TYPE between", value1, value2, "type");
  310. return (Criteria) this;
  311. }
  312. public Criteria andTypeNotBetween(Integer value1, Integer value2) {
  313. addCriterion("TYPE not between", value1, value2, "type");
  314. return (Criteria) this;
  315. }
  316. public Criteria andLaunchDateIsNull() {
  317. addCriterion("LAUNCH_DATE is null");
  318. return (Criteria) this;
  319. }
  320. public Criteria andLaunchDateIsNotNull() {
  321. addCriterion("LAUNCH_DATE is not null");
  322. return (Criteria) this;
  323. }
  324. public Criteria andLaunchDateEqualTo(Date value) {
  325. addCriterionForJDBCDate("LAUNCH_DATE =", value, "launchDate");
  326. return (Criteria) this;
  327. }
  328. public Criteria andLaunchDateNotEqualTo(Date value) {
  329. addCriterionForJDBCDate("LAUNCH_DATE <>", value, "launchDate");
  330. return (Criteria) this;
  331. }
  332. public Criteria andLaunchDateGreaterThan(Date value) {
  333. addCriterionForJDBCDate("LAUNCH_DATE >", value, "launchDate");
  334. return (Criteria) this;
  335. }
  336. public Criteria andLaunchDateGreaterThanOrEqualTo(Date value) {
  337. addCriterionForJDBCDate("LAUNCH_DATE >=", value, "launchDate");
  338. return (Criteria) this;
  339. }
  340. public Criteria andLaunchDateLessThan(Date value) {
  341. addCriterionForJDBCDate("LAUNCH_DATE <", value, "launchDate");
  342. return (Criteria) this;
  343. }
  344. public Criteria andLaunchDateLessThanOrEqualTo(Date value) {
  345. addCriterionForJDBCDate("LAUNCH_DATE <=", value, "launchDate");
  346. return (Criteria) this;
  347. }
  348. public Criteria andLaunchDateIn(List<Date> values) {
  349. addCriterionForJDBCDate("LAUNCH_DATE in", values, "launchDate");
  350. return (Criteria) this;
  351. }
  352. public Criteria andLaunchDateNotIn(List<Date> values) {
  353. addCriterionForJDBCDate("LAUNCH_DATE not in", values, "launchDate");
  354. return (Criteria) this;
  355. }
  356. public Criteria andLaunchDateBetween(Date value1, Date value2) {
  357. addCriterionForJDBCDate("LAUNCH_DATE between", value1, value2, "launchDate");
  358. return (Criteria) this;
  359. }
  360. public Criteria andLaunchDateNotBetween(Date value1, Date value2) {
  361. addCriterionForJDBCDate("LAUNCH_DATE not between", value1, value2, "launchDate");
  362. return (Criteria) this;
  363. }
  364. public Criteria andModifiedIsNull() {
  365. addCriterion("MODIFIED is null");
  366. return (Criteria) this;
  367. }
  368. public Criteria andModifiedIsNotNull() {
  369. addCriterion("MODIFIED is not null");
  370. return (Criteria) this;
  371. }
  372. public Criteria andModifiedEqualTo(Date value) {
  373. addCriterion("MODIFIED =", value, "modified");
  374. return (Criteria) this;
  375. }
  376. public Criteria andModifiedNotEqualTo(Date value) {
  377. addCriterion("MODIFIED <>", value, "modified");
  378. return (Criteria) this;
  379. }
  380. public Criteria andModifiedGreaterThan(Date value) {
  381. addCriterion("MODIFIED >", value, "modified");
  382. return (Criteria) this;
  383. }
  384. public Criteria andModifiedGreaterThanOrEqualTo(Date value) {
  385. addCriterion("MODIFIED >=", value, "modified");
  386. return (Criteria) this;
  387. }
  388. public Criteria andModifiedLessThan(Date value) {
  389. addCriterion("MODIFIED <", value, "modified");
  390. return (Criteria) this;
  391. }
  392. public Criteria andModifiedLessThanOrEqualTo(Date value) {
  393. addCriterion("MODIFIED <=", value, "modified");
  394. return (Criteria) this;
  395. }
  396. public Criteria andModifiedIn(List<Date> values) {
  397. addCriterion("MODIFIED in", values, "modified");
  398. return (Criteria) this;
  399. }
  400. public Criteria andModifiedNotIn(List<Date> values) {
  401. addCriterion("MODIFIED not in", values, "modified");
  402. return (Criteria) this;
  403. }
  404. public Criteria andModifiedBetween(Date value1, Date value2) {
  405. addCriterion("MODIFIED between", value1, value2, "modified");
  406. return (Criteria) this;
  407. }
  408. public Criteria andModifiedNotBetween(Date value1, Date value2) {
  409. addCriterion("MODIFIED not between", value1, value2, "modified");
  410. return (Criteria) this;
  411. }
  412. public Criteria andCreatedIsNull() {
  413. addCriterion("CREATED is null");
  414. return (Criteria) this;
  415. }
  416. public Criteria andCreatedIsNotNull() {
  417. addCriterion("CREATED is not null");
  418. return (Criteria) this;
  419. }
  420. public Criteria andCreatedEqualTo(Date value) {
  421. addCriterion("CREATED =", value, "created");
  422. return (Criteria) this;
  423. }
  424. public Criteria andCreatedNotEqualTo(Date value) {
  425. addCriterion("CREATED <>", value, "created");
  426. return (Criteria) this;
  427. }
  428. public Criteria andCreatedGreaterThan(Date value) {
  429. addCriterion("CREATED >", value, "created");
  430. return (Criteria) this;
  431. }
  432. public Criteria andCreatedGreaterThanOrEqualTo(Date value) {
  433. addCriterion("CREATED >=", value, "created");
  434. return (Criteria) this;
  435. }
  436. public Criteria andCreatedLessThan(Date value) {
  437. addCriterion("CREATED <", value, "created");
  438. return (Criteria) this;
  439. }
  440. public Criteria andCreatedLessThanOrEqualTo(Date value) {
  441. addCriterion("CREATED <=", value, "created");
  442. return (Criteria) this;
  443. }
  444. public Criteria andCreatedIn(List<Date> values) {
  445. addCriterion("CREATED in", values, "created");
  446. return (Criteria) this;
  447. }
  448. public Criteria andCreatedNotIn(List<Date> values) {
  449. addCriterion("CREATED not in", values, "created");
  450. return (Criteria) this;
  451. }
  452. public Criteria andCreatedBetween(Date value1, Date value2) {
  453. addCriterion("CREATED between", value1, value2, "created");
  454. return (Criteria) this;
  455. }
  456. public Criteria andCreatedNotBetween(Date value1, Date value2) {
  457. addCriterion("CREATED not between", value1, value2, "created");
  458. return (Criteria) this;
  459. }
  460. }
  461. public static class Criteria extends GeneratedCriteria {
  462. protected Criteria() {
  463. super();
  464. }
  465. }
  466. public static class Criterion {
  467. private String condition;
  468. private Object value;
  469. private Object secondValue;
  470. private boolean noValue;
  471. private boolean singleValue;
  472. private boolean betweenValue;
  473. private boolean listValue;
  474. private String typeHandler;
  475. public String getCondition() {
  476. return condition;
  477. }
  478. public Object getValue() {
  479. return value;
  480. }
  481. public Object getSecondValue() {
  482. return secondValue;
  483. }
  484. public boolean isNoValue() {
  485. return noValue;
  486. }
  487. public boolean isSingleValue() {
  488. return singleValue;
  489. }
  490. public boolean isBetweenValue() {
  491. return betweenValue;
  492. }
  493. public boolean isListValue() {
  494. return listValue;
  495. }
  496. public String getTypeHandler() {
  497. return typeHandler;
  498. }
  499. protected Criterion(String condition) {
  500. super();
  501. this.condition = condition;
  502. this.typeHandler = null;
  503. this.noValue = true;
  504. }
  505. protected Criterion(String condition, Object value, String typeHandler) {
  506. super();
  507. this.condition = condition;
  508. this.value = value;
  509. this.typeHandler = typeHandler;
  510. if (value instanceof List<?>) {
  511. this.listValue = true;
  512. } else {
  513. this.singleValue = true;
  514. }
  515. }
  516. protected Criterion(String condition, Object value) {
  517. this(condition, value, null);
  518. }
  519. protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
  520. super();
  521. this.condition = condition;
  522. this.value = value;
  523. this.secondValue = secondValue;
  524. this.typeHandler = typeHandler;
  525. this.betweenValue = true;
  526. }
  527. protected Criterion(String condition, Object value, Object secondValue) {
  528. this(condition, value, secondValue, null);
  529. }
  530. }
  531. }

Dao: WorkerNodeMapper

  1. package org.com.spi.dao;
  2. import java.util.List;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.apache.ibatis.annotations.Param;
  5. import org.com.spi.model.WorkerNode;
  6. import org.com.spi.model.WorkerNodeExample;
  7. @Mapper
  8. public interface WorkerNodeMapper {
  9. int countByExample(WorkerNodeExample example);
  10. int deleteByExample(WorkerNodeExample example);
  11. int deleteByPrimaryKey(Long id);
  12. int insert(WorkerNode record);
  13. int insertSelective(WorkerNode record);
  14. List<WorkerNode> selectByExample(WorkerNodeExample example);
  15. WorkerNode selectByPrimaryKey(Long id);
  16. int updateByExampleSelective(@Param("record") WorkerNode record, @Param("example") WorkerNodeExample example);
  17. int updateByExample(@Param("record") WorkerNode record, @Param("example") WorkerNodeExample example);
  18. int updateByPrimaryKeySelective(WorkerNode record);
  19. int updateByPrimaryKey(WorkerNode record);
  20. }

三, 配置文件 及 xml

配置文件内容:

  1. spring.datasource.url=jdbc:mysql://localhost:3306/generate_id?characterEncoding=utf8&serverTimezone=UTC
  2. # ??????
  3. spring.datasource.username=root
  4. # ?????
  5. spring.datasource.password=root
  6. # ?????
  7. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  8. ###################################### MyBatis ??######################################
  9. # ?? mapper.xml ???
  10. mybatis.mapper-locations=classpath:mybatis/*.xml
  11. #????????,?????????????? mapper.xml ??????????????
  12. mybatis.type-aliases-package=net.biancheng.www.bean
  13. #???????????????????
  14. mybatis.configuration.map-underscore-to-camel-case=true

在resources/mybatis目录下创建WorkerNodeMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="org.com.spi.dao.WorkerNodeMapper" >
  4. <resultMap id="BaseResultMap" type="org.com.spi.model.WorkerNode" >
  5. <id column="ID" property="id" jdbcType="BIGINT" />
  6. <result column="HOST_NAME" property="hostName" jdbcType="VARCHAR" />
  7. <result column="PORT" property="port" jdbcType="VARCHAR" />
  8. <result column="TYPE" property="type" jdbcType="INTEGER" />
  9. <result column="LAUNCH_DATE" property="launchDate" jdbcType="DATE" />
  10. <result column="MODIFIED" property="modified" jdbcType="TIMESTAMP" />
  11. <result column="CREATED" property="created" jdbcType="TIMESTAMP" />
  12. </resultMap>
  13. <sql id="Example_Where_Clause" >
  14. <where >
  15. <foreach collection="oredCriteria" item="criteria" separator="or" >
  16. <if test="criteria.valid" >
  17. <trim prefix="(" suffix=")" prefixOverrides="and" >
  18. <foreach collection="criteria.criteria" item="criterion" >
  19. <choose >
  20. <when test="criterion.noValue" >
  21. and ${criterion.condition}
  22. </when>
  23. <when test="criterion.singleValue" >
  24. and ${criterion.condition} #{criterion.value}
  25. </when>
  26. <when test="criterion.betweenValue" >
  27. and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
  28. </when>
  29. <when test="criterion.listValue" >
  30. and ${criterion.condition}
  31. <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
  32. #{listItem}
  33. </foreach>
  34. </when>
  35. </choose>
  36. </foreach>
  37. </trim>
  38. </if>
  39. </foreach>
  40. </where>
  41. </sql>
  42. <sql id="Update_By_Example_Where_Clause" >
  43. <where >
  44. <foreach collection="example.oredCriteria" item="criteria" separator="or" >
  45. <if test="criteria.valid" >
  46. <trim prefix="(" suffix=")" prefixOverrides="and" >
  47. <foreach collection="criteria.criteria" item="criterion" >
  48. <choose >
  49. <when test="criterion.noValue" >
  50. and ${criterion.condition}
  51. </when>
  52. <when test="criterion.singleValue" >
  53. and ${criterion.condition} #{criterion.value}
  54. </when>
  55. <when test="criterion.betweenValue" >
  56. and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
  57. </when>
  58. <when test="criterion.listValue" >
  59. and ${criterion.condition}
  60. <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
  61. #{listItem}
  62. </foreach>
  63. </when>
  64. </choose>
  65. </foreach>
  66. </trim>
  67. </if>
  68. </foreach>
  69. </where>
  70. </sql>
  71. <sql id="Base_Column_List" >
  72. ID, HOST_NAME, PORT, TYPE, LAUNCH_DATE, MODIFIED, CREATED
  73. </sql>
  74. <select id="selectByExample" resultMap="BaseResultMap" parameterType="org.com.spi.model.WorkerNodeExample" >
  75. select
  76. <if test="distinct" >
  77. distinct
  78. </if>
  79. <include refid="Base_Column_List" />
  80. from worker_node
  81. <if test="_parameter != null" >
  82. <include refid="Example_Where_Clause" />
  83. </if>
  84. <if test="orderByClause != null" >
  85. order by ${orderByClause}
  86. </if>
  87. </select>
  88. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
  89. select
  90. <include refid="Base_Column_List" />
  91. from worker_node
  92. where ID = #{id,jdbcType=BIGINT}
  93. </select>
  94. <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
  95. delete from worker_node
  96. where ID = #{id,jdbcType=BIGINT}
  97. </delete>
  98. <delete id="deleteByExample" parameterType="org.com.spi.model.WorkerNodeExample" >
  99. delete from worker_node
  100. <if test="_parameter != null" >
  101. <include refid="Example_Where_Clause" />
  102. </if>
  103. </delete>
  104. <insert id="insert" parameterType="org.com.spi.model.WorkerNode" >
  105. insert into worker_node (ID, HOST_NAME, PORT,
  106. TYPE, LAUNCH_DATE, MODIFIED,
  107. CREATED)
  108. values (#{id,jdbcType=BIGINT}, #{hostName,jdbcType=VARCHAR}, #{port,jdbcType=VARCHAR},
  109. #{type,jdbcType=INTEGER}, #{launchDate,jdbcType=DATE}, #{modified,jdbcType=TIMESTAMP},
  110. #{created,jdbcType=TIMESTAMP})
  111. </insert>
  112. <insert id="insertSelective" parameterType="org.com.spi.model.WorkerNode" >
  113. insert into worker_node
  114. <trim prefix="(" suffix=")" suffixOverrides="," >
  115. <if test="id != null" >
  116. ID,
  117. </if>
  118. <if test="hostName != null" >
  119. HOST_NAME,
  120. </if>
  121. <if test="port != null" >
  122. PORT,
  123. </if>
  124. <if test="type != null" >
  125. TYPE,
  126. </if>
  127. <if test="launchDate != null" >
  128. LAUNCH_DATE,
  129. </if>
  130. <if test="modified != null" >
  131. MODIFIED,
  132. </if>
  133. <if test="created != null" >
  134. CREATED,
  135. </if>
  136. </trim>
  137. <trim prefix="values (" suffix=")" suffixOverrides="," >
  138. <if test="id != null" >
  139. #{id,jdbcType=BIGINT},
  140. </if>
  141. <if test="hostName != null" >
  142. #{hostName,jdbcType=VARCHAR},
  143. </if>
  144. <if test="port != null" >
  145. #{port,jdbcType=VARCHAR},
  146. </if>
  147. <if test="type != null" >
  148. #{type,jdbcType=INTEGER},
  149. </if>
  150. <if test="launchDate != null" >
  151. #{launchDate,jdbcType=DATE},
  152. </if>
  153. <if test="modified != null" >
  154. #{modified,jdbcType=TIMESTAMP},
  155. </if>
  156. <if test="created != null" >
  157. #{created,jdbcType=TIMESTAMP},
  158. </if>
  159. </trim>
  160. </insert>
  161. <select id="countByExample" parameterType="org.com.spi.model.WorkerNodeExample" resultType="java.lang.Integer" >
  162. select count(*) from worker_node
  163. <if test="_parameter != null" >
  164. <include refid="Example_Where_Clause" />
  165. </if>
  166. </select>
  167. <update id="updateByExampleSelective" parameterType="map" >
  168. update worker_node
  169. <set >
  170. <if test="record.id != null" >
  171. ID = #{record.id,jdbcType=BIGINT},
  172. </if>
  173. <if test="record.hostName != null" >
  174. HOST_NAME = #{record.hostName,jdbcType=VARCHAR},
  175. </if>
  176. <if test="record.port != null" >
  177. PORT = #{record.port,jdbcType=VARCHAR},
  178. </if>
  179. <if test="record.type != null" >
  180. TYPE = #{record.type,jdbcType=INTEGER},
  181. </if>
  182. <if test="record.launchDate != null" >
  183. LAUNCH_DATE = #{record.launchDate,jdbcType=DATE},
  184. </if>
  185. <if test="record.modified != null" >
  186. MODIFIED = #{record.modified,jdbcType=TIMESTAMP},
  187. </if>
  188. <if test="record.created != null" >
  189. CREATED = #{record.created,jdbcType=TIMESTAMP},
  190. </if>
  191. </set>
  192. <if test="_parameter != null" >
  193. <include refid="Update_By_Example_Where_Clause" />
  194. </if>
  195. </update>
  196. <update id="updateByExample" parameterType="map" >
  197. update worker_node
  198. set ID = #{record.id,jdbcType=BIGINT},
  199. HOST_NAME = #{record.hostName,jdbcType=VARCHAR},
  200. PORT = #{record.port,jdbcType=VARCHAR},
  201. TYPE = #{record.type,jdbcType=INTEGER},
  202. LAUNCH_DATE = #{record.launchDate,jdbcType=DATE},
  203. MODIFIED = #{record.modified,jdbcType=TIMESTAMP},
  204. CREATED = #{record.created,jdbcType=TIMESTAMP}
  205. <if test="_parameter != null" >
  206. <include refid="Update_By_Example_Where_Clause" />
  207. </if>
  208. </update>
  209. <update id="updateByPrimaryKeySelective" parameterType="org.com.spi.model.WorkerNode" >
  210. update worker_node
  211. <set >
  212. <if test="hostName != null" >
  213. HOST_NAME = #{hostName,jdbcType=VARCHAR},
  214. </if>
  215. <if test="port != null" >
  216. PORT = #{port,jdbcType=VARCHAR},
  217. </if>
  218. <if test="type != null" >
  219. TYPE = #{type,jdbcType=INTEGER},
  220. </if>
  221. <if test="launchDate != null" >
  222. LAUNCH_DATE = #{launchDate,jdbcType=DATE},
  223. </if>
  224. <if test="modified != null" >
  225. MODIFIED = #{modified,jdbcType=TIMESTAMP},
  226. </if>
  227. <if test="created != null" >
  228. CREATED = #{created,jdbcType=TIMESTAMP},
  229. </if>
  230. </set>
  231. where ID = #{id,jdbcType=BIGINT}
  232. </update>
  233. <update id="updateByPrimaryKey" parameterType="org.com.spi.model.WorkerNode" >
  234. update worker_node
  235. set HOST_NAME = #{hostName,jdbcType=VARCHAR},
  236. PORT = #{port,jdbcType=VARCHAR},
  237. TYPE = #{type,jdbcType=INTEGER},
  238. LAUNCH_DATE = #{launchDate,jdbcType=DATE},
  239. MODIFIED = #{modified,jdbcType=TIMESTAMP},
  240. CREATED = #{created,jdbcType=TIMESTAMP}
  241. where ID = #{id,jdbcType=BIGINT}
  242. </update>
  243. </mapper>

四, 编写相关类

入口类: DefaultUidGenerator

  1. package org.com.spi.utils.baidu;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.InitializingBean;
  5. import org.springframework.util.StringUtils;
  6. import java.net.InetAddress;
  7. import java.net.UnknownHostException;
  8. import java.util.Date;
  9. import java.util.concurrent.TimeUnit;
  10. public class DefaultUidGenerator implements UidGenerator, InitializingBean {
  11. private static final Logger LOGGER = LoggerFactory.getLogger(DefaultUidGenerator.class);
  12. /** Bits allocate */
  13. protected int timeBits = 28;
  14. protected int workerBits = 22;
  15. protected int seqBits = 13;
  16. /** Customer epoch, unit as second. For example 2016-05-20 (ms: 1463673600000)*/
  17. protected String epochStr = "2016-05-20";
  18. protected long epochSeconds = TimeUnit.MILLISECONDS.toSeconds(1463673600000L);
  19. /** Stable fields after spring bean initializing */
  20. protected BitsAllocator bitsAllocator;
  21. protected long workerId;
  22. /** Volatile fields caused by nextId() */
  23. protected long sequence = 0L;
  24. protected long lastSecond = -1L;
  25. // /** Spring property */
  26. // protected WorkerIdAssigner workerIdAssigner;
  27. public long getWorkerId() {
  28. return workerId;
  29. }
  30. public void setWorkerId(long workerId) {
  31. this.workerId = workerId;
  32. }
  33. @Override
  34. public void afterPropertiesSet() throws Exception {
  35. // initialize bits allocator
  36. bitsAllocator = new BitsAllocator(timeBits, workerBits, seqBits);
  37. // // initialize worker id
  38. // workerId = workerIdAssigner.assignWorkerId();
  39. if (workerId > bitsAllocator.getMaxWorkerId()) {
  40. throw new RuntimeException("Worker id " + workerId + " exceeds the max " + bitsAllocator.getMaxWorkerId());
  41. }
  42. LOGGER.info("Initialized bits(1, {}, {}, {}) for workerID:{}", timeBits, workerBits, seqBits, workerId);
  43. }
  44. @Override
  45. public long getUID() throws UidGenerateException {
  46. try {
  47. return nextId();
  48. } catch (Exception e) {
  49. LOGGER.error("Generate unique id exception. ", e);
  50. throw new UidGenerateException(e);
  51. }
  52. }
  53. @Override
  54. public String parseUID(long uid) {
  55. long totalBits = BitsAllocator.TOTAL_BITS;
  56. long signBits = bitsAllocator.getSignBits();
  57. long timestampBits = bitsAllocator.getTimestampBits();
  58. long workerIdBits = bitsAllocator.getWorkerIdBits();
  59. long sequenceBits = bitsAllocator.getSequenceBits();
  60. // parse UID
  61. long sequence = (uid << (totalBits - sequenceBits)) >>> (totalBits - sequenceBits);
  62. long workerId = (uid << (timestampBits + signBits)) >>> (totalBits - workerIdBits);
  63. long deltaSeconds = uid >>> (workerIdBits + sequenceBits);
  64. Date thatTime = new Date(TimeUnit.SECONDS.toMillis(epochSeconds + deltaSeconds));
  65. String thatTimeStr = DateUtils.formatByDateTimePattern(thatTime);
  66. // format as string
  67. return String.format("{\"UID\":\"%d\",\"timestamp\":\"%s\",\"workerId\":\"%d\",\"sequence\":\"%d\"}",
  68. uid, thatTimeStr, workerId, sequence);
  69. }
  70. /**
  71. * Get UID
  72. *
  73. * @return UID
  74. * @throws UidGenerateException in the case: Clock moved backwards; Exceeds the max timestamp
  75. */
  76. protected synchronized long nextId() {
  77. long currentSecond = getCurrentSecond();
  78. // Clock moved backwards, refuse to generate uid
  79. if (currentSecond < lastSecond) {
  80. long refusedSeconds = lastSecond - currentSecond;
  81. throw new UidGenerateException("Clock moved backwards. Refusing for %d seconds", refusedSeconds);
  82. }
  83. // At the same second, increase sequence
  84. if (currentSecond == lastSecond) {
  85. sequence = (sequence + 1) & bitsAllocator.getMaxSequence();
  86. // Exceed the max sequence, we wait the next second to generate uid
  87. if (sequence == 0) {
  88. currentSecond = getNextSecond(lastSecond);
  89. }
  90. // At the different second, sequence restart from zero
  91. } else {
  92. sequence = 0L;
  93. }
  94. lastSecond = currentSecond;
  95. // Allocate bits for UID
  96. return bitsAllocator.allocate(currentSecond - epochSeconds, workerId, sequence);
  97. }
  98. /**
  99. * Get next millisecond
  100. */
  101. private long getNextSecond(long lastTimestamp) {
  102. long timestamp = getCurrentSecond();
  103. while (timestamp <= lastTimestamp) {
  104. timestamp = getCurrentSecond();
  105. }
  106. return timestamp;
  107. }
  108. /**
  109. * Get current second
  110. */
  111. private long getCurrentSecond() {
  112. long currentSecond = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
  113. if (currentSecond - epochSeconds > bitsAllocator.getMaxDeltaSeconds()) {
  114. throw new UidGenerateException("Timestamp bits is exhausted. Refusing UID generate. Now: " + currentSecond);
  115. }
  116. return currentSecond;
  117. }
  118. /**
  119. * Setters for spring property
  120. */
  121. // public void setWorkerIdAssigner(WorkerIdAssigner workerIdAssigner) {
  122. // this.workerIdAssigner = workerIdAssigner;
  123. // }
  124. public void setTimeBits(int timeBits) {
  125. if (timeBits > 0) {
  126. this.timeBits = timeBits;
  127. }
  128. }
  129. public void setWorkerBits(int workerBits) {
  130. if (workerBits > 0) {
  131. this.workerBits = workerBits;
  132. }
  133. }
  134. public void setSeqBits(int seqBits) {
  135. if (seqBits > 0) {
  136. this.seqBits = seqBits;
  137. }
  138. }
  139. public void setEpochStr(String epochStr) {
  140. if (StringUtils.hasLength(epochStr)) {
  141. this.epochStr = epochStr;
  142. this.epochSeconds = TimeUnit.MILLISECONDS.toSeconds(DateUtils.parseByDayPattern(epochStr).getTime());
  143. }
  144. }
  145. public String getPodIp(){
  146. try {
  147. InetAddress localHost = InetAddress.getLocalHost();
  148. return localHost.getHostAddress();
  149. } catch (UnknownHostException e) {
  150. e.printStackTrace();
  151. }
  152. return "127.0.0.1";
  153. }
  154. }

接口: UidGenerator

  1. package org.com.spi.utils.baidu;
  2. public interface UidGenerator {
  3. /**
  4. * Get a unique ID
  5. *
  6. * @return UID
  7. * @throws UidGenerateException
  8. */
  9. long getUID() throws UidGenerateException;
  10. /**
  11. * Parse the UID into elements which are used to generate the UID. <br>
  12. * Such as timestamp & workerId & sequence...
  13. *
  14. * @param uid
  15. * @return Parsed info
  16. */
  17. String parseUID(long uid);
  18. }

接口WorkerIdAssigner:

  1. package org.com.spi.utils.baidu;
  2. public interface WorkerIdAssigner {
  3. /**
  4. * @return assigned worker id
  5. */
  6. long assignWorkerId();
  7. }

BitsAllocator类:

  1. package org.com.spi.utils.baidu;
  2. import org.apache.commons.lang3.builder.ToStringBuilder;
  3. import org.apache.commons.lang3.builder.ToStringStyle;
  4. import org.springframework.util.Assert;
  5. public class BitsAllocator {
  6. /**
  7. * Total 64 bits
  8. */
  9. public static final int TOTAL_BITS = 1 << 6;
  10. /**
  11. * Bits for [sign-> second-> workId-> sequence]
  12. */
  13. private int signBits = 1;
  14. private final int timestampBits;
  15. private final int workerIdBits;
  16. private final int sequenceBits;
  17. /**
  18. * Max value for workId & sequence
  19. */
  20. private final long maxDeltaSeconds;
  21. private final long maxWorkerId;
  22. private final long maxSequence;
  23. /**
  24. * Shift for timestamp & workerId
  25. */
  26. private final int timestampShift;
  27. private final int workerIdShift;
  28. /**
  29. * Constructor with timestampBits, workerIdBits, sequenceBits<br>
  30. * The highest bit used for sign, so <code>63</code> bits for timestampBits, workerIdBits, sequenceBits
  31. */
  32. public BitsAllocator(int timestampBits, int workerIdBits, int sequenceBits) {
  33. // make sure allocated 64 bits
  34. int allocateTotalBits = signBits + timestampBits + workerIdBits + sequenceBits;
  35. Assert.isTrue(allocateTotalBits == TOTAL_BITS, "allocate not enough 64 bits");
  36. // initialize bits
  37. this.timestampBits = timestampBits;
  38. this.workerIdBits = workerIdBits;
  39. this.sequenceBits = sequenceBits;
  40. // initialize max value
  41. this.maxDeltaSeconds = ~(-1L << timestampBits);
  42. this.maxWorkerId = ~(-1L << workerIdBits);
  43. this.maxSequence = ~(-1L << sequenceBits);
  44. // initialize shift
  45. this.timestampShift = workerIdBits + sequenceBits;
  46. this.workerIdShift = sequenceBits;
  47. }
  48. /**
  49. * Allocate bits for UID according to delta seconds & workerId & sequence<br>
  50. * <b>Note that: </b>The highest bit will always be 0 for sign
  51. *
  52. * @param deltaSeconds
  53. * @param workerId
  54. * @param sequence
  55. * @return
  56. */
  57. public long allocate(long deltaSeconds, long workerId, long sequence) {
  58. return (deltaSeconds << timestampShift) | (workerId << workerIdShift) | sequence;
  59. }
  60. /**
  61. * Getters
  62. */
  63. public int getSignBits() {
  64. return signBits;
  65. }
  66. public int getTimestampBits() {
  67. return timestampBits;
  68. }
  69. public int getWorkerIdBits() {
  70. return workerIdBits;
  71. }
  72. public int getSequenceBits() {
  73. return sequenceBits;
  74. }
  75. public long getMaxDeltaSeconds() {
  76. return maxDeltaSeconds;
  77. }
  78. public long getMaxWorkerId() {
  79. return maxWorkerId;
  80. }
  81. public long getMaxSequence() {
  82. return maxSequence;
  83. }
  84. public int getTimestampShift() {
  85. return timestampShift;
  86. }
  87. public int getWorkerIdShift() {
  88. return workerIdShift;
  89. }
  90. @Override
  91. public String toString() {
  92. return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
  93. }
  94. }

异常类UidGenerateException:

  1. package org.com.spi.utils.baidu;
  2. public class UidGenerateException extends RuntimeException {
  3. /**
  4. * Serial Version UID
  5. */
  6. private static final long serialVersionUID = -27048199131316992L;
  7. /**
  8. * Default constructor
  9. */
  10. public UidGenerateException() {
  11. super();
  12. }
  13. /**
  14. * Constructor with message & cause
  15. *
  16. * @param message
  17. * @param cause
  18. */
  19. public UidGenerateException(String message, Throwable cause) {
  20. super(message, cause);
  21. }
  22. /**
  23. * Constructor with message
  24. *
  25. * @param message
  26. */
  27. public UidGenerateException(String message) {
  28. super(message);
  29. }
  30. /**
  31. * Constructor with message format
  32. *
  33. * @param msgFormat
  34. * @param args
  35. */
  36. public UidGenerateException(String msgFormat, Object... args) {
  37. super(String.format(msgFormat, args));
  38. }
  39. /**
  40. * Constructor with cause
  41. *
  42. * @param cause
  43. */
  44. public UidGenerateException(Throwable cause) {
  45. super(cause);
  46. }
  47. }

配置类: UidGeneratorConfig

  1. package org.com.spi.config;
  2. import org.com.spi.dao.WorkerNodeMapper;
  3. import org.com.spi.enums.ProjectTypeEnum;
  4. import org.com.spi.model.WorkerNode;
  5. import org.com.spi.model.WorkerNodeExample;
  6. import org.com.spi.utils.ListUtils;
  7. import org.com.spi.utils.baidu.DefaultUidGenerator;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.context.annotation.Configuration;
  12. import java.util.Date;
  13. import java.util.List;
  14. @Configuration
  15. public class UidGeneratorConfig {
  16. @Autowired
  17. private WorkerNodeMapper workerNodeMapper;
  18. @Value("${server.port}")
  19. private String port;
  20. @Bean
  21. public DefaultUidGenerator defaultUidGenerator(){
  22. DefaultUidGenerator defaultUidGenerator = new DefaultUidGenerator();
  23. String podIp = defaultUidGenerator.getPodIp();
  24. System.out.println("ip:"+podIp+",port:"+port);
  25. //是否已存在workId
  26. WorkerNodeExample example = new WorkerNodeExample();
  27. example.createCriteria().andHostNameEqualTo(podIp)
  28. .andPortEqualTo(port);
  29. List<WorkerNode> workerNodes = workerNodeMapper.selectByExample(example);
  30. WorkerNode workerNode = null;
  31. if(!ListUtils.anyList(workerNodes)){
  32. //新增
  33. Date date = new Date();
  34. workerNode = new WorkerNode();
  35. workerNode.setCreated(date);
  36. workerNode.setHostName(podIp);
  37. workerNode.setModified(date);
  38. workerNode.setLaunchDate(date);
  39. workerNode.setPort(port);
  40. workerNode.setType(ProjectTypeEnum.DEMO.getType());
  41. int i = workerNodeMapper.insertSelective(workerNode);
  42. if(i > 0){
  43. workerNodes = workerNodeMapper.selectByExample(example);
  44. workerNode = workerNodes.get(0);
  45. }
  46. }else{
  47. workerNode = workerNodes.get(0);
  48. }
  49. defaultUidGenerator.setWorkerId(workerNode.getId());
  50. return defaultUidGenerator;
  51. }
  52. }

日期时间处理类DateUtils:

  1. package org.com.spi.utils.baidu;
  2. import org.apache.commons.lang.time.DateFormatUtils;
  3. import java.text.ParseException;
  4. import java.util.Calendar;
  5. import java.util.Date;
  6. public abstract class DateUtils extends org.apache.commons.lang.time.DateUtils {
  7. /**
  8. * Patterns
  9. */
  10. public static final String DAY_PATTERN = "yyyy-MM-dd";
  11. public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
  12. public static final String DATETIME_MS_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
  13. public static final Date DEFAULT_DATE = DateUtils.parseByDayPattern("1970-01-01");
  14. /**
  15. * Parse date by 'yyyy-MM-dd' pattern
  16. *
  17. * @param str
  18. * @return
  19. */
  20. public static Date parseByDayPattern(String str) {
  21. return parseDate(str, DAY_PATTERN);
  22. }
  23. /**
  24. * Parse date by 'yyyy-MM-dd HH:mm:ss' pattern
  25. *
  26. * @param str
  27. * @return
  28. */
  29. public static Date parseByDateTimePattern(String str) {
  30. return parseDate(str, DATETIME_PATTERN);
  31. }
  32. /**
  33. * Parse date without Checked exception
  34. *
  35. * @param str
  36. * @param pattern
  37. * @return
  38. * @throws RuntimeException when ParseException occurred
  39. */
  40. public static Date parseDate(String str, String pattern) {
  41. try {
  42. return parseDate(str, new String[]{pattern});
  43. } catch (ParseException e) {
  44. throw new RuntimeException(e);
  45. }
  46. }
  47. /**
  48. * Format date into string
  49. *
  50. * @param date
  51. * @param pattern
  52. * @return
  53. */
  54. public static String formatDate(Date date, String pattern) {
  55. return DateFormatUtils.format(date, pattern);
  56. }
  57. /**
  58. * Format date by 'yyyy-MM-dd' pattern
  59. *
  60. * @param date
  61. * @return
  62. */
  63. public static String formatByDayPattern(Date date) {
  64. if (date != null) {
  65. return DateFormatUtils.format(date, DAY_PATTERN);
  66. } else {
  67. return null;
  68. }
  69. }
  70. /**
  71. * Format date by 'yyyy-MM-dd HH:mm:ss' pattern
  72. *
  73. * @param date
  74. * @return
  75. */
  76. public static String formatByDateTimePattern(Date date) {
  77. return DateFormatUtils.format(date, DATETIME_PATTERN);
  78. }
  79. /**
  80. * Get current day using format date by 'yyyy-MM-dd HH:mm:ss' pattern
  81. *
  82. * @return
  83. * @author yebo
  84. */
  85. public static String getCurrentDayByDayPattern() {
  86. Calendar cal = Calendar.getInstance();
  87. return formatByDayPattern(cal.getTime());
  88. }
  89. }

特点: 百度Uid generator是基于雪花算法实现,不同点在于其workId是动态的,即不同机器生成的workId不同,将主键ID作为wrokId,在项目启动时完成workId的生成及获取.遗憾的是 目前百度的这个开源算法已经停止了维护!

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/202684
推荐阅读
相关标签
  

闽ICP备14008679号