blob: af8f3ec8d2c68affa2b7fda29a50dbf09ceef008 [file] [log] [blame]
package lookup
import (
"net"
"sync"
"time"
)
import (
"github.com/apache/dubbo-kubernetes/pkg/core"
)
type cacheRecord struct {
ips []net.IP
creationTime time.Time
}
func CachedLookupIP(f LookupIPFunc, ttl time.Duration) LookupIPFunc {
cache := map[string]*cacheRecord{}
var rwmux sync.RWMutex
return func(host string) ([]net.IP, error) {
rwmux.RLock()
r, ok := cache[host]
rwmux.RUnlock()
if ok && r.creationTime.Add(ttl).After(core.Now()) {
return r.ips, nil
}
ips, err := f(host)
if err != nil {
return nil, err
}
rwmux.Lock()
cache[host] = &cacheRecord{ips: ips, creationTime: core.Now()}
rwmux.Unlock()
return ips, nil
}
}