1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether.named.redisson;
20
21 import javax.inject.Named;
22 import javax.inject.Singleton;
23
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.concurrent.TimeUnit;
27
28 import org.eclipse.aether.named.NamedLock;
29 import org.eclipse.aether.named.NamedLockKey;
30 import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock;
31 import org.redisson.api.RSemaphore;
32
33
34
35
36 @Singleton
37 @Named(RedissonSemaphoreNamedLockFactory.NAME)
38 public class RedissonSemaphoreNamedLockFactory extends RedissonNamedLockFactorySupport {
39 public static final String NAME = "semaphore-redisson";
40
41 private static final String TYPED_NAME_PREFIX = NAME_PREFIX + NAME + ":";
42
43 private final ConcurrentMap<NamedLockKey, RSemaphore> semaphores;
44
45 public RedissonSemaphoreNamedLockFactory() {
46 this.semaphores = new ConcurrentHashMap<>();
47 }
48
49 @Override
50 protected AdaptedSemaphoreNamedLock createLock(final NamedLockKey key) {
51 RSemaphore semaphore = semaphores.computeIfAbsent(key, k -> {
52 RSemaphore result = redissonClient.getSemaphore(TYPED_NAME_PREFIX + k.name());
53 if (!result.trySetPermits(Integer.MAX_VALUE)) {
54 logger.warn("Failed to set permits on semaphore '{}'; it may be in a stale state", k.name());
55 }
56 return result;
57 });
58 return new AdaptedSemaphoreNamedLock(key, this, new RedissonSemaphore(semaphore));
59 }
60
61 @Override
62 protected void destroyLock(final NamedLock namedLock) {
63 if (namedLock instanceof AdaptedSemaphoreNamedLock) {
64 final NamedLockKey key = namedLock.key();
65 RSemaphore semaphore = semaphores.remove(key);
66 if (semaphore == null) {
67 throw new IllegalStateException("Semaphore expected, but does not exist: " + key);
68 }
69
70
71
72 }
73 }
74
75 private static final class RedissonSemaphore implements AdaptedSemaphoreNamedLock.AdaptedSemaphore {
76 private final RSemaphore semaphore;
77
78 private RedissonSemaphore(final RSemaphore semaphore) {
79 this.semaphore = semaphore;
80 }
81
82 @Override
83 public boolean tryAcquire(final int perms, final long time, final TimeUnit unit) throws InterruptedException {
84 return semaphore.tryAcquire(perms, time, unit);
85 }
86
87 @Override
88 public void release(final int perms) {
89 semaphore.release(perms);
90 }
91 }
92 }