#
zhou zhou
16 小时以前 c1c045cad0f39a38409de117e9ddf470804b0d81
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
package com.vincent.rsf.server.manager.service.impl;
 
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
 
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Arrays;
 
@Slf4j
@Service
@RequiredArgsConstructor
public class WmsRedisLuaService {
 
    private static final DefaultRedisScript<Long> LOCATION_CLAIM_SCRIPT = createScript("wms-lua/location-claim.lua");
    private static final DefaultRedisScript<Long> INVENTORY_RESERVE_SCRIPT = createScript("wms-lua/inventory-reserve.lua");
 
    private final StringRedisTemplate redisTemplate;
 
    public boolean claimLocation(String occupyKey, String taskKey, String mode, String occupyValue, String taskValue, Duration ttl) {
        Long result = redisTemplate.execute(
                LOCATION_CLAIM_SCRIPT,
                Arrays.asList(occupyKey, taskKey),
                mode,
                occupyValue,
                taskValue,
                String.valueOf(ttl.toMillis())
        );
        return result != null && result > 0;
    }
 
    public boolean reserveInventory(String inventoryKey, String orderKey, BigDecimal initialAvailable, BigDecimal reserveQuantity, Duration ttl) {
        Long result = redisTemplate.execute(
                INVENTORY_RESERVE_SCRIPT,
                Arrays.asList(inventoryKey, orderKey),
                initialAvailable.toPlainString(),
                reserveQuantity.toPlainString(),
                String.valueOf(ttl.toMillis())
        );
        return result != null && result > 0;
    }
 
    public void releaseKeys(String... keys) {
        if (keys == null || keys.length == 0) {
            return;
        }
        try {
            redisTemplate.delete(Arrays.asList(keys));
        } catch (Exception ex) {
            log.warn("Release redis keys failed", ex);
        }
    }
 
    public void resetInventoryCache(String inventoryKey, BigDecimal availableQuantity, Duration ttl) {
        redisTemplate.opsForValue().set(inventoryKey, availableQuantity.toPlainString(), ttl);
    }
 
    private static DefaultRedisScript<Long> createScript(String path) {
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setLocation(new ClassPathResource(path));
        script.setResultType(Long.class);
        return script;
    }
}