RedisService.java
2.05 KB
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
package cn.com.glsx.stdinterface.modules.service;
import com.glsx.plat.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Calendar;
import java.util.Date;
@Service
public class RedisService {
private static final String REDIS_GLOBAL_ORDER_ID = "NES_GLOBAL_ORDER_ID_";
@Autowired
private RedisUtils redisUtils;
/**
* Redis生成数据库全局唯一性id
*
* @return
*/
public Long getGlobalUniqueId() {
String orderIdPrefix = this.getOrderIdPrefix(new Date());
Long id = this.orderId(orderIdPrefix);
return id;
}
/**
* 获取年的后两位加上一年多少天+当前小时数作为前缀
*
* @param date
* @return
*/
public String getOrderIdPrefix(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
//补两位,因为一年最多三位数
String monthFormat = String.format("%1$02d", month + 1);
//补两位,因为日最多两位数
String dayFormat = String.format("%1$02d", day);
//补两位,因为小时最多两位数
String hourFormat = String.format("%1$02d", hour);
return year + monthFormat + dayFormat + hourFormat;
}
/**
* 生成订单
*
* @param prefix
* @return
*/
public Long orderId(String prefix) {
String key = REDIS_GLOBAL_ORDER_ID + prefix;
String orderId = null;
try {
Long increment = redisUtils.incr(key, 1);
//往前补6位
orderId = prefix + String.format("%1$06d", increment);
} catch (Exception e) {
System.out.println("生成订单号失败");
e.printStackTrace();
}
return Long.valueOf(orderId);
}
}