SyncCouponSendNumService.java
2.52 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
71
72
73
74
75
76
77
78
package com.yohoufo.promotion.service;
import com.google.common.collect.Sets;
import com.yohoufo.promotion.common.Constant;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class SyncCouponSendNumService {
private static final Logger logger = LoggerFactory.getLogger(SyncCouponSendNumService.class);
/**
* 是否正在运行,防止任务重复执行
*/
private static volatile boolean IS_RUNNING = false;
/**
* 优惠券ID set集合
*/
private static Set<String> COUPON_TOKEN_SET = Sets.newConcurrentHashSet();
@Autowired
private SingleCentCouponService singleCentSyncCoupNumService;
public static void addCouponToken(String couponToken) {
COUPON_TOKEN_SET.add(couponToken);
}
/**
* 前一次任务执行完5分钟后再执行,且任务中又随机睡10分钟,将redis中的领用数量同步到DB中持久化
*/
@Scheduled(fixedDelay = Constant.SYNC_COUPON_SEND_NUM_REDIS_2_DB)
public synchronized void syncCouponSendNumRedis2DB() {
if (IS_RUNNING) {
logger.info("sync send num to db task is running");
return;
}
try {
IS_RUNNING = true;
int sleepSeconds = new Random().nextInt(600);
logger.info("sync coupon send num just sleep:{}s", sleepSeconds);
TimeUnit.SECONDS.sleep(sleepSeconds);
if (CollectionUtils.isEmpty(COUPON_TOKEN_SET)) {
logger.info("no coupons send num need sync");
}
Iterator<String> iterator = COUPON_TOKEN_SET.iterator();
for (; iterator.hasNext(); ) {
String couponToken = iterator.next();
try {
if (singleCentSyncCoupNumService.syncCoupSendNum(couponToken)) {
iterator.remove();
}
} catch (Exception e) {
logger.error("sync coupon send num error:{},{}", couponToken, e.getMessage());
}
}
} catch (Exception e) {
logger.error("sync send coupon num error:{}", e.getMessage());
} finally {
IS_RUNNING = false;
}
}
}