io.cdap.plugin.common.script.CachingLookup Maven / Gradle / Ivy
/*
* Copyright © 2015-2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.common.script;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import io.cdap.cdap.etl.api.CacheConfig;
import io.cdap.cdap.etl.api.Lookup;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* {@link Lookup} that provides caching over a delegate.
*
* @param the type of object that will be returned for a lookup
*/
public class CachingLookup implements Lookup {
private final Lookup delegate;
private final LoadingCache cache;
public CachingLookup(final Lookup delegate, CacheConfig cacheConfig) {
this.delegate = delegate;
this.cache = CacheBuilder.newBuilder()
.maximumSize(cacheConfig.getMaxSize())
.expireAfterWrite(cacheConfig.getExpirySeconds(), TimeUnit.SECONDS)
.build(new CacheLoader() {
@Override
public T load(String key) throws Exception {
return delegate.lookup(key);
}
});
}
@Override
public T lookup(String key) {
return cache.getUnchecked(key);
}
@Override
public Map lookup(String... keys) {
return lookup(ImmutableSet.copyOf(keys));
}
@Override
public Map lookup(Set keys) {
ImmutableMap cached = cache.getAllPresent(keys);
Set missingKeys = Sets.difference(keys, cached.keySet());
Map missing = delegate.lookup(missingKeys);
cache.putAll(missing);
return ImmutableMap.builder()
.putAll(cached)
.putAll(missing)
.build();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy