分库分表时一般有必要自定义生成uuid,大企业一般有自己的uuid生成服务,其他它的实现很简单。我们以订单号为例,组成可以是"业务标识号+年月日+当日自增数字格式化",如0001201608140000020。当然,如果我们用"业务标识号+用户唯一标识+当前时间"也是可以达到uuid的目的的,但用户唯一标识是敏感信息且可能不太方便处理为数字,所以弄一套uuid生成服务是很有必要的。本文就来研究下怎么实现自增数字,且性能能满足企业中的多方业务调用。起初,我想的是db+redis,后来想想用redis不仅会相对降低稳定性,更是一种舍近求远的做法,所以,我最终的做法是db+本地缓存(内存)。不说了,直接上代码。

public class uuidmodel implements serializable {
private static final long serialversionuid = 972714740313784893l;
private string name;
private long start;
private long end;
// above is db column
private long oldstart;
private long oldend;
private long now;

package com.itlong.bjxizhan.uuid;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import java.util.list;
import java.util.concurrent.concurrenthashmap;
import java.util.concurrent.concurrentmap;
/**
* created by shenhongxi on 2016/8/12.
*/
public class uuidcontext {
private static final logger log = loggerfactory.getlogger(uuidcontext.class);
// 缓存db中的截止数
public static concurrentmap<string, long> endcache = new concurrenthashmap<string,long>();
// 缓存当前增加到的数值
public static concurrentmap<string, long> nowcache = new concurrenthashmap<string,long>();
// 缓存共享对象
public static concurrentmap<string, uuidmodel> uuidcache = new concurrenthashmap<string, uuidmodel>();
// 缓存配置
public static concurrentmap<string, config> configcache = new concurrenthashmap<string, config>();
static uuiddao uuiddao;
/**
* 根据名称更新号段 直至成功
* @param um
* @return
*/
public static uuidmodel updateuuid(uuidmodel um, int length){
boolean updated = false;
do{
uuidmodel _um = uuiddao.findbyname(um.getname());
int cachesize = 1000;
config config = getconfig(um.getname());
if (config != null) {
cachesize = config.getcachesize();
}
// 判断是否需要重置 条件为:1.配置的重置数<新段的截止数 则需要重置
// 2.新段的截止数大于需要获取的位数 则需要重置
long resetnum = config.getresetnum();
// 取得新段的截止数
long newend = _um.getend() + cachesize;
um.setoldend(_um.getend());
um.setoldstart(_um.getstart());
if ((resetnum < newend) || (string.valueof(newend).length() > length)) {
// 需要重置为0开始段
um.setstart(0);
um.setend(cachesize);
} else {
// 取新段
um.setstart(_um.getend());
um.setend(_um.getend() + cachesize);
// 最终的更新成功保证了多实例部署时,各实例持有的号段不同
updated = uuiddao.update(um);
} while (!updated);
return um;
}
* 载入内存
public static void loadmemory(uuidmodel um){
endcache.put(um.getname(), um.getend());
nowcache.put(um.getname(), um.getstart());
uuidcache.put(um.getname(), um);
public static config getconfig(string name) {
config config = configcache.get(name);
if (config == null) {
config = configcache.get("default");
}
return config;
}

import java.text.simpledateformat;
import java.util.date;
public class uuidserviceimpl implements uuidservice {
private static final logger log = loggerfactory.getlogger(uuidserviceimpl.class);
private uuiddao uuiddao;
@override
public string nextuuid(string name) {
// 日期 + format(nextuuid(name, cachesize, length))
private synchronized long nextuuid(string name, int cachesize, int length) {
uuidmodel um = uuidcontext.uuidcache.get(name);
long nowuuid = null;
try {
if (um != null) {
synchronized (um) {
nowuuid = uuidcontext.nowcache.get(name);
config cm = uuidcontext.getconfig(name);
// 判断是否到达预警值
if (uuidcontext.nowcache.get(name).intvalue() == cm.getwarnnum()) {
log.warn("警告:" + name + "号段已达到预警值.");
}
log.info("dbnum:" + uuidcontext.endcache.get(name)
+ ",nownum:" + uuidcontext.nowcache.get(name));
// 判断内存中号段是否用完
if (uuidcontext.nowcache.get(name).compareto(uuidcontext.endcache.get(name)) >= 0) {
// 更新号段
uuidcontext.updateuuid(um, length);
nowuuid = um.getstart() + 1;
uuidcontext.endcache.put(name, um.getend());
uuidcontext.nowcache.put(name, nowuuid);
} else {
nowuuid += 1;
// 是否需要重置 判断自增号位数是否大于length参数
if (string.valueof(nowuuid).length() > length) {
// 更新号段,需要重置
nowuuid = 1l;
uuidcontext.updateuuid(um, 0);
uuidcontext.endcache.put(name, um.getend());
uuidcontext.nowcache.put(name, nowuuid);
uuidcontext.uuidcache.put(name, um);
} else {
// 直接修改缓存的值就可以了
}
}
synchronized (this) {
um = uuidcontext.uuidcache.get(name);
if (um != null) {
return nextuuid(name, cachesize, length);
nowuuid = 1l;
// 如果缓存不存在,那么就新增到数据库
uuidmodel um2 = new uuidmodel();
um2.setname(name);
um2.setstart(0);
um2.setend(cachesize);
uuiddao.insert(um2);
// 还要同时在缓存的map中加入
uuidcontext.endcache.put(name, um2.getend());
uuidcontext.nowcache.put(name, nowuuid);
uuidcontext.uuidcache.put(name, um2);
} catch (exception e) {
log.error("生成uuid error", e);
if (e.getmessage() != null && (e.getmessage().indexof("unique key") >= 0 ||
e.getmessage().indexof("primary key") >= 0)) {
uuidmodel _um = new uuidmodel();
_um.setname(name);
// 更新号段
uuidcontext.updateuuid(_um, length);
// 载入缓存
uuidcontext.loadmemory(_um);
// 继续获取
return nextuuid(name, cachesize, length);
throw new runtimeexception("生成uuid error");
return nowuuid;
值得一提的是,db+本地缓存的思路同样可以用于抢购时的库存计算。
原文链接:[http://wely.iteye.com/blog/2317423]