simplify get code

This commit is contained in:
Asim Aslam 2018-12-18 18:06:34 +00:00
parent 770c16a66d
commit 67d10e5f39

View File

@ -81,16 +81,25 @@ func (c *cacheSelector) del(service string) {
} }
func (c *cacheSelector) get(service string) ([]*registry.Service, error) { func (c *cacheSelector) get(service string) ([]*registry.Service, error) {
// read lock for the duration // read lock
c.RLock() c.RLock()
// watch service if not watched // check the cache first
if _, ok := c.watched[service]; !ok { services, ok := c.cache[service]
go c.run(service) // get cache ttl
ttl, kk := c.ttls[service]
// got services && within ttl so return cache
if ok && kk && time.Since(ttl) < c.ttl {
// make a copy
cp := c.cp(services)
// unlock the read
c.RUnlock()
// return servics
return cp, nil
} }
// get does the actual request for a service // get does the actual request for a service and cache it
// it also caches it
get := func(service string) ([]*registry.Service, error) { get := func(service string) ([]*registry.Service, error) {
// ask the registry // ask the registry
services, err := c.so.Registry.GetService(service) services, err := c.so.Registry.GetService(service)
@ -106,52 +115,16 @@ func (c *cacheSelector) get(service string) ([]*registry.Service, error) {
return services, nil return services, nil
} }
// check the cache first // watch service if not watched
services, ok := c.cache[service] if _, ok := c.watched[service]; !ok {
// make a copy go c.run(service)
cp := c.cp(services)
// cache miss or no services
if !ok || len(services) == 0 {
// unlock the read
c.RUnlock()
// get and return services
return get(service)
} }
// got cache but lets check ttl // unlock the read lock
ttl, kk := c.ttls[service]
// within ttl so return cache
if kk && time.Since(ttl) < c.ttl {
// unlock the read
c.RUnlock()
// return servics
return cp, nil
}
// unlock read
c.RUnlock() c.RUnlock()
// expired entry so get service // get and return services
rservices, err := get(service) return get(service)
// no error then return services
if err == nil {
return rservices, nil
}
// not found error then return
if err == registry.ErrNotFound {
return nil, selector.ErrNotFound
}
// other error
// return expired cache copy as last resort
return cp, nil
} }
func (c *cacheSelector) set(service string, services []*registry.Service) { func (c *cacheSelector) set(service string, services []*registry.Service) {