-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAsyncCacheableMethodProcessor.java
44 lines (38 loc) · 1.63 KB
/
AsyncCacheableMethodProcessor.java
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
package com.async.cacheable.manager;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.async.cacheable.annotation.AsyncCacheable;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@RequiredArgsConstructor
@Component
public class AsyncCacheableMethodProcessor implements BeanPostProcessor {
private final AsyncCacheManager asyncCacheManager;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
Arrays.stream(bean.getClass().getDeclaredMethods())
.filter(m -> m.isAnnotationPresent(AsyncCacheable.class))
.forEach(
m -> {
AsyncCacheable asyncCacheable = m.getAnnotation(AsyncCacheable.class);
String cacheName = asyncCacheable.name();
long expireAfterWriteSeconds = asyncCacheable.expireAfterWriteSeconds();
long maximumSize = asyncCacheable.maximumSize();
String cacheIdentifier =
"%s_%s_%s".formatted(cacheName, expireAfterWriteSeconds, maximumSize);
asyncCacheManager.computeIfAbsent(
cacheIdentifier,
(key) -> {
return Caffeine.newBuilder()
.maximumSize(maximumSize)
.expireAfterWrite(expireAfterWriteSeconds, TimeUnit.SECONDS)
.buildAsync();
});
});
return bean;
}
}