前言
公司有一個發(fā)券的接口有并發(fā)安全問題,下面列出這個問題和解決這個問題的方式。
業(yè)務(wù)描述
這個接口的作用是給會員發(fā)多張券碼。涉及到4張主體,分別是:用戶,券,券碼,用戶領(lǐng)取記錄。
下面是改造前的偽代碼。
主要是因為查出券碼那行存在并發(fā)安全問題,多個線程拿到同幾個券碼。以下都是基于如何讓取券碼變成原子的去展開。
1
2
3
4
5
6
7
8
9
10
11
12
|
public boolean sendCoupons(Long userId, Long couponId) { // 一堆校驗 // ... // 查出券碼 List<CouponCode> couponCodes = couponCodeService.findByCouponId(couponId, num); // batchUpdateStatus是一個被@Transactional(propagation = Propagation.REQUIRES_NEW)修飾的方法 // 批量更新為已被領(lǐng)取狀態(tài) couponCodeService.batchUpdateStatus(couponCods); // 發(fā)券 // 發(fā)權(quán)益 // 新增用戶券碼領(lǐng)取記錄 } |
改造過程
因為券碼是多張,想用lua+redis的list結(jié)構(gòu)去做彈出。為什么用這種方案是因為for update直接被否了。
這是寫的lua腳本。。
1
2
3
4
5
|
local result = {} for i=1,ARGV[1],1 do result[i] = redis.call("lpop", KEYS[1]) end return table.contact(result , "|") |
這是寫的執(zhí)行l(wèi)ua腳本的client。。其實主要的解決方法就是在redis的list里rpush(存),lpop(取)取數(shù)據(jù)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
@Slf4j @Component public class CouponCodeRedisQueueClient implements InitializingBean { /** * redis lua腳本文件路徑 */ public static final String POP_COUPON_CODE_LUA_PATH = "lua/pop-coupon-code.lua"; public static final String SEPARATOR = "|"; private static final String COUPON_CODE_KEY_PATTERN = "PROMOTION:COUPON_CODE_{0}"; private String LUA_COUPON_CODE_SCRIPT; private String LUA_COUPON_CODE_SCRIPT_SHA; @Autowired private JedisTemplate jedisTemplate; @Override public void afterPropertiesSet() throws Exception { LUA_COUPON_CODE_SCRIPT = Resources.toString(Resources.getResource(POP_COUPON_CODE_LUA_PATH), Charsets.UTF_8); if (StringUtils.isNotBlank(LUA_COUPON_CODE_SCRIPT)) { LUA_COUPON_CODE_SCRIPT_SHA = jedisTemplate.execute(jedis -> { return jedis.scriptLoad(LUA_COUPON_CODE_SCRIPT); }); log.info("redis lock script sha:{}", LUA_COUPON_CODE_SCRIPT_SHA); } } /** * 獲取Code * * @param activityId * @param num * @return */ public List<String> popCouponCode(Long activityId, String num , int retryNum) { if(retryNum == 0){ log.error("reload lua script error , try limit times ,activityId:{}", activityId); return Collections.emptyList(); } List<String> keys = Lists.newArrayList(); String key = buildKey(String.valueOf(activityId)); keys.add(key); List<String> args = Lists.newArrayList(); args.add(num); try { Object result = jedisTemplate.execute(jedis -> { if (StringUtils.isNotBlank(LUA_COUPON_CODE_SCRIPT_SHA)) { return jedis.evalsha(LUA_COUPON_CODE_SCRIPT_SHA, keys, args); } else { return jedis.eval(LUA_COUPON_CODE_SCRIPT, keys, args); } }); log.info("pop coupon code by lua script.result:{}", result); if (Objects.isNull(result)) { return Collections.emptyList(); } return Splitter.on(SEPARATOR).splitToList(result.toString()); } catch (JedisNoScriptException jnse) { log.error("no lua lock script found.try to reload it", jnse); reloadLuaScript(); //加載后重新執(zhí)行 popCouponCode(activityId, num, --retryNum); } catch (Exception e) { log.error("failed to get a redis lock.key:{}", key, e); } return Collections.emptyList(); } /** * 重新加載LUA腳本 * * @throws Exception */ public void reloadLuaScript() { synchronized (CouponCodeRedisQueueClient.class) { try { afterPropertiesSet(); } catch (Exception e) { log.error("failed to reload redis lock lua script.retry load it."); reloadLuaScript(); } } } /** * 構(gòu)建Key * * @param activityId * @return */ public String buildKey(String activityId) { return MessageFormat.format(COUPON_CODE_KEY_PATTERN, activityId); } } |
當(dāng)然這種操作需要去提前把所有券的券碼丟到redis里去,這里我們也碰到了一些問題(券碼量比較大的情況下)。比如開始直接粗暴的用@PostConstruct去放入redis,導(dǎo)致項目啟動需要很久很久。。這里就不展開了,說一下我們嘗試的幾種方法
- @PostConstruct注解
- CommandLineRunner接口
- redis的pipeline技術(shù)
- 先保證每個卡券有一定量的券碼在redis,再用定時任務(wù)定時(根據(jù)業(yè)務(wù)量)去補
到此這篇關(guān)于使用lua+redis解決發(fā)多張券的并發(fā)問題的文章就介紹到這了,更多相關(guān)redis多張券的并發(fā)內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.cnblogs.com/gistmap/p/14256794.html