cache peers/nodes

This commit is contained in:
Carsten Otto
2021-11-19 20:50:16 +01:00
parent e6b2e74891
commit 5bbcd56f49
2 changed files with 24 additions and 4 deletions

View File

@@ -10,13 +10,18 @@ import org.springframework.stereotype.Component;
@Component
public class NodeService {
private static final int MAXIMUM_SIZE = 500;
private static final int CACHE_EXPIRY_MINUTES = 30;
private static final int ALIAS_CACHE_EXPIRY_MINUTES = 30;
private static final int NODE_CACHE_EXPIRY_SECONDS = 60;
private final GrpcNodeInfo grpcNodeInfo;
private final LoadingCache<Pubkey, String> aliasCache = new CacheBuilder()
.withExpiryMinutes(CACHE_EXPIRY_MINUTES)
.withExpiryMinutes(ALIAS_CACHE_EXPIRY_MINUTES)
.withMaximumSize(MAXIMUM_SIZE)
.build(this::getAliasWithoutCache);
private final LoadingCache<Pubkey, Node> nodeCache = new CacheBuilder()
.withExpirySeconds(NODE_CACHE_EXPIRY_SECONDS)
.withMaximumSize(MAXIMUM_SIZE)
.build(this::getNodeWithoutCache);
public NodeService(GrpcNodeInfo grpcNodeInfo) {
this.grpcNodeInfo = grpcNodeInfo;
@@ -27,11 +32,17 @@ public class NodeService {
}
public Node getNode(Pubkey pubkey) {
return grpcNodeInfo.getNode(pubkey);
return nodeCache.getUnchecked(pubkey);
}
private Node getNodeWithoutCache(Pubkey pubkey) {
Node node = grpcNodeInfo.getNode(pubkey);
aliasCache.put(pubkey, node.alias());
return node;
}
private String getAliasWithoutCache(Pubkey pubkey) {
return getNode(pubkey).alias();
return getNodeWithoutCache(pubkey).alias();
}
}

View File

@@ -9,6 +9,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
import static de.cotto.lndmanagej.model.NodeFixtures.ALIAS;
import static de.cotto.lndmanagej.model.NodeFixtures.NODE;
import static de.cotto.lndmanagej.model.NodeFixtures.NODE_WITHOUT_ALIAS;
import static de.cotto.lndmanagej.model.PubkeyFixtures.PUBKEY;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@@ -32,4 +33,12 @@ class NodeServiceTest {
when(grpcNodeInfo.getNode(PUBKEY)).thenReturn(NODE);
assertThat(nodeService.getNode(PUBKEY)).isEqualTo(NODE);
}
@Test
void getNode_updates_alias() {
when(grpcNodeInfo.getNode(PUBKEY)).thenReturn(NODE_WITHOUT_ALIAS).thenReturn(NODE).thenThrow();
assertThat(nodeService.getAlias(PUBKEY)).isEqualTo(NODE_WITHOUT_ALIAS.alias());
nodeService.getNode(PUBKEY);
assertThat(nodeService.getAlias(PUBKEY)).isEqualTo(ALIAS);
}
}