p2p: add cache for func PacketConn.relayPeer

This commit is contained in:
rkonfj
2025-02-15 20:47:12 +08:00
parent 88a2870174
commit 1476061b60
2 changed files with 24 additions and 20 deletions

2
cache/cache.go vendored
View File

@@ -33,7 +33,7 @@ var (
)
func init() {
defaultCache = lru.New[string, *CacheValue[any]](1024)
defaultCache = lru.New[string, *CacheValue[any]](2048)
}
// LoadTTL load value by key from default cache pool

View File

@@ -13,6 +13,7 @@ import (
"sync/atomic"
"time"
"github.com/sigcn/pg/cache"
"github.com/sigcn/pg/cache/lru"
"github.com/sigcn/pg/disco"
"github.com/sigcn/pg/disco/udp"
@@ -265,6 +266,7 @@ func (c *PacketConn) PeerMeta(peerID disco.PeerID) url.Values {
// relayPeer find the suitable relay peer
func (c *PacketConn) relayPeer(peerID disco.PeerID) disco.PeerID {
selectRelayPeer := func(_ string) disco.PeerID {
peers := c.PeerStore().Peers()
for range len(peers) {
index := c.relayPeerIndex.Add(1) % uint64(len(peers))
@@ -286,6 +288,8 @@ func (c *PacketConn) relayPeer(peerID disco.PeerID) disco.PeerID {
}
}
return ""
}
return cache.LoadTTL(peerID.String(), time.Millisecond, selectRelayPeer)
}
// networkChangeDetect listen network change and restart udp and websocket listener