liguangix 2018-08-10
利用redis的单线程高速缓存特性生成序列号,订单号,之后入库
String orderNo = PREFIX + factoryService.createTradeNo();
/**
* 定义TradeNo的生成
* @return
*/
public String createTradeNo(){
return dataFactory.getUID(BankConstants.BANKAPI_BANK_TRADENO);
}
/**
* 获取唯一id (固定长度20位)
*
* @param key redis key
* @return
*/
public String getUID(String key) {
int sufLength = ranLen;
return redisIdByDate(key, sufLength);
}
/**
* 获取唯一id 时间+自增序列
*
* @param key redis key
* @param sufLength 自增的位数
* @return
*/
public String redisIdByDate(String key, int sufLength) {
//获取时间戳
String dateTime = "";
String incr = "";
List<String> time = null;
try {
time = jedisTemple.time();
if (time != null && time.get(0) != null) {
dateTime = TimeUtils.TimeStamp2Date(time.get(0), BankConstants.time1);
} else {
dateTime = BankConstants.sdf_time1.format(new Date());
log.error(LogUtils.print("未获取到REDIS时间,请及时解决..."));
}
} catch (Exception e) {
dateTime = BankConstants.sdf_time1.format(new Date());
log.error(LogUtils.print("未获取到REDIS时间,请及时解决..."), e);
}
//获取redis自增
try {
incr = incrId(key, sufLength);
} catch (Exception e) {
incr = String.valueOf(random(sufLength));
log.error(LogUtils.print("key=" + key, "", "获取REDIS自增ID时异常,请及时解决..."), e);
}
log.info(String.format("KEY[%s],时间[%s]+自增ID[%s]=UID[%s]", key, dateTime, incr, dateTime + incr));
return dateTime + incr;
}