Junhc

岂止于博客

分布式全局ID生成方案

数据库生成
DROP TABLE IF EXISTS `installer_sequence`;
CREATE TABLE `installer_sequence` (
  `seq_name` varchar(255) NOT NULL,
  `min_value` bigint(15) NOT NULL,
  `max_value` bigint(15) NOT NULL,
  `current_val` bigint(15) NOT NULL,
  `increment_val` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`seq_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP FUNCTION IF EXISTS `seq_nextval`;
delimiter ;;
CREATE FUNCTION `seq_nextval`(`NAME` VARCHAR(255)) RETURNS bigint(20)
BEGIN
DECLARE _cur BIGINT;
DECLARE _maxvalue BIGINT;
UPDATE installer_sequence
SET current_val = current_val + increment_val
WHERE
	seq_name = `NAME`;

SELECT
	current_val,
	max_value INTO _cur,
	_maxvalue
FROM
	installer_sequence
WHERE
	seq_name = `NAME`;
IF (_cur >= _maxvalue) THEN
	UPDATE installer_sequence
SET current_val = minvalue
WHERE
	seq_name = `NAME`;
END
IF;
RETURN _cur;
END;
;;
delimiter ;
参考资料