This repository has been archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(caching): add rate triggered MyBatis database caching. (#213)
* feat(caching): add rate triggered MyBatis database caching. * chore: update default settings and docs * fix: grammer in cache docs * refactor: use Metric Reporting Cache instead of duplicating logic
- Loading branch information
Showing
16 changed files
with
569 additions
and
13 deletions.
There are no files selected for viewing
207 changes: 207 additions & 0 deletions
207
src/main/java/com/nike/cerberus/cache/DatabaseCache.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,207 @@ | ||
/* | ||
* Copyright (c) 2019 Nike, 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 com.nike.cerberus.cache; | ||
|
||
import com.codahale.metrics.Counter; | ||
import com.google.common.collect.ImmutableMap; | ||
import com.google.inject.Injector; | ||
import com.nike.cerberus.server.config.guice.StaticInjector; | ||
import com.nike.cerberus.service.MetricsService; | ||
import com.typesafe.config.Config; | ||
import org.apache.commons.lang3.StringUtils; | ||
import org.apache.ibatis.builder.InitializingObject; | ||
import org.apache.ibatis.cache.Cache; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
import java.util.Objects; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.concurrent.locks.ReadWriteLock; | ||
|
||
import static com.github.benmanes.caffeine.cache.Caffeine.newBuilder; | ||
import static java.util.Optional.ofNullable; | ||
|
||
/** | ||
* This is a custom MyBatis Cache, that allows use to do the following | ||
* 1. Report cache statistics via Dropwizard | ||
* 2. Expire items automatically after some TTL from when they were cached. (To avoid needing to deal with distributed cache busting, this basically makes cached data eventually consistent up to the defined TTL) | ||
* 3. Only cache items after it has been proven via repeat reads that they should be cached. (To avoid unnecessary eventual consistency in the dashboard, only make the items under heavy reads eventually consistent) | ||
* See cms.conf for all the configuration settings. | ||
*/ | ||
public class DatabaseCache implements Cache, InitializingObject { | ||
|
||
private final Logger log = LoggerFactory.getLogger(getClass()); | ||
private Integer repeatReadThreshold; | ||
|
||
protected static final String GLOBAL_DATA_TTL_IN_SECONDS = "cms.mybatis.cache.global.dataTtlInSeconds"; | ||
protected static final String DATA_TTL_IN_SECONDS_OVERRIDE_PATH_TEMPLATE = "cms.mybatis.cache.%s.dataTtlInSeconds"; | ||
protected static final String GLOBAL_REPEAT_READ_COUNTER_EXPIRE_IN_SECONDS = "cms.mybatis.cache.global.repeatReadCounterResetInSeconds"; | ||
protected static final String REPEAT_READ_COUNTER_EXPIRE_IN_SECONDS_OVERRIDE_PATH_TEMPLATE = "cms.mybatis.cache.%s.repeatReadCounterResetInSeconds"; | ||
protected static final String GLOBAL_REPEAT_READ_THRESHOLD = "cms.mybatis.cache.global.repeatReadThreshold"; | ||
protected static final String REPEAT_READ_THRESHOLD_OVERRIDE_PATH_TEMPLATE = "cms.mybatis.cache.%s.repeatReadThreshold"; | ||
protected static final int DEFAULT_GLOBAL_DATA_TTL_IN_SECONDS = 10; | ||
protected static final int DEFAULT_REPEAT_READ_COUNTER_EXPIRE_IN_SECONDS = 2; | ||
protected static final int DEFAULT_REPEAT_READ_THRESHOLD = 2; | ||
|
||
protected final String id; | ||
protected MetricReportingCache<Object, Object> dataCache; | ||
protected com.github.benmanes.caffeine.cache.Cache<Object, Counter> autoExpiringRepeatReadCounterMap; | ||
|
||
public DatabaseCache(String id) { | ||
this.id = id; | ||
} | ||
|
||
/** | ||
* This method gets called after this class is instantiated by MyBatis and all the properties have been set. | ||
*/ | ||
@Override | ||
public void initialize() { | ||
// Util we can get the MyBatis Guice Module updated, this is our best bet, for getting the Guice instances. | ||
// https://groups.google.com/forum/#!msg/mybatis-user/Ekd1LTNVIDc/t2xGuvETBgAJ | ||
Injector injector = StaticInjector.getInstance(); | ||
|
||
Config config = injector.getInstance(Config.class); | ||
MetricsService metricsService = injector.getInstance(MetricsService.class); | ||
|
||
String mapperKey = StringUtils.uncapitalize(id.replaceFirst("com.nike.cerberus.mapper.", "")); | ||
int expireTimeInSeconds = getExpireTimeInSeconds(config, mapperKey); | ||
int counterExpireTimeInSeconds = getRepeatReadCounterExpireTimeInSeconds(config, mapperKey); | ||
repeatReadThreshold = getRepeatReadThreshold(config, mapperKey); | ||
|
||
log.info("Database cache created with mapperKey: {}, expireTimeInSeconds: {}, counterExpireTimeInSeconds: {}, repeatReadThreshold: {}", | ||
mapperKey, expireTimeInSeconds, counterExpireTimeInSeconds, repeatReadThreshold); | ||
|
||
dataCache = new MetricReportingCache<>("mybatis", expireTimeInSeconds, metricsService, | ||
ImmutableMap.of("namespace", this.id)); | ||
|
||
autoExpiringRepeatReadCounterMap = newBuilder() | ||
.expireAfterAccess(counterExpireTimeInSeconds, TimeUnit.SECONDS) | ||
.build(); | ||
} | ||
|
||
/** | ||
* @param config The application config | ||
* @param mapperKey The key for this mapper | ||
* @return The amount of time in seconds that the mapper cache will keep an item in memory before it purges itself. | ||
*/ | ||
protected int getExpireTimeInSeconds(Config config, String mapperKey) { | ||
int globalExpireTimeInSeconds = config.hasPath(GLOBAL_DATA_TTL_IN_SECONDS) ? config.getInt(GLOBAL_DATA_TTL_IN_SECONDS) : DEFAULT_GLOBAL_DATA_TTL_IN_SECONDS; | ||
String globalDataTtlInSecondsOverridePathTemplate = String.format(DATA_TTL_IN_SECONDS_OVERRIDE_PATH_TEMPLATE, mapperKey); | ||
return config.hasPath(globalDataTtlInSecondsOverridePathTemplate) ? config.getInt(globalDataTtlInSecondsOverridePathTemplate) : globalExpireTimeInSeconds; | ||
} | ||
|
||
/** | ||
* @param config The application config | ||
* @param mapperKey The key for this mapper | ||
* @return The amount of time in seconds that must pass without consecutive reads to reset the counter. | ||
*/ | ||
protected int getRepeatReadCounterExpireTimeInSeconds(Config config, String mapperKey) { | ||
int globalCounterExpireTimeInSeconds = config.hasPath(GLOBAL_REPEAT_READ_COUNTER_EXPIRE_IN_SECONDS) ? config.getInt(GLOBAL_REPEAT_READ_COUNTER_EXPIRE_IN_SECONDS) : DEFAULT_REPEAT_READ_COUNTER_EXPIRE_IN_SECONDS; | ||
String counterMapperOverrideTtlPath = String.format(REPEAT_READ_COUNTER_EXPIRE_IN_SECONDS_OVERRIDE_PATH_TEMPLATE, mapperKey); | ||
return config.hasPath(counterMapperOverrideTtlPath) ? config.getInt(counterMapperOverrideTtlPath) : globalCounterExpireTimeInSeconds; | ||
} | ||
|
||
/** | ||
* @param config The application config | ||
* @param mapperKey The key for this mapper | ||
* @return The number of reads that must be exceeding while counts are being chained before caching of that object is enabled. | ||
*/ | ||
protected int getRepeatReadThreshold(Config config, String mapperKey) { | ||
int globalRepeatReadThreshold = config.hasPath(GLOBAL_REPEAT_READ_THRESHOLD) ? config.getInt(GLOBAL_REPEAT_READ_THRESHOLD) : DEFAULT_REPEAT_READ_THRESHOLD; | ||
String repeatReadThresholdOverridePath = String.format(REPEAT_READ_THRESHOLD_OVERRIDE_PATH_TEMPLATE, mapperKey); | ||
return config.hasPath(repeatReadThresholdOverridePath) ? config.getInt(repeatReadThresholdOverridePath) : globalRepeatReadThreshold; | ||
} | ||
|
||
@Override | ||
public String getId() { | ||
return id; | ||
} | ||
|
||
@Override | ||
public void putObject(Object key, Object value) { | ||
if (key == null || value == null) { | ||
return; | ||
} | ||
|
||
// If the read counter exists and is greater than the threshold then we are receiving | ||
// burst repeat reads and we will cache that entry. | ||
ofNullable(autoExpiringRepeatReadCounterMap.getIfPresent(key)).ifPresent(counter -> { | ||
if (counter.getCount() > repeatReadThreshold) { | ||
dataCache.put(key, value); | ||
} | ||
}); | ||
} | ||
|
||
@Override | ||
public Object getObject(Object key) { | ||
// Increment the read counter, which resets after counterExpireTimeInSeconds. | ||
Counter counter = autoExpiringRepeatReadCounterMap.getIfPresent(key); | ||
if (counter != null) { | ||
counter.inc(); | ||
} else { | ||
counter = new Counter(); | ||
counter.inc(); | ||
autoExpiringRepeatReadCounterMap.put(key, counter); | ||
} | ||
|
||
return dataCache.getIfPresent(key); | ||
} | ||
|
||
@Override | ||
public Object removeObject(Object key) { | ||
Object res = dataCache.getIfPresent(key); | ||
dataCache.invalidate(key); | ||
return res; | ||
} | ||
|
||
@Override | ||
public void clear() { | ||
// NO-OP, my batis by default clears the entire namespaced cache when a write action occurs, | ||
// we do not want that here, we are expiring the cache / making reads eventually consistent. | ||
// Since we run Cerberus in a cluster anyways and each instance will have it's own generated cache, a simple small | ||
// time window where items purge themselves is adequate. | ||
} | ||
|
||
@Override | ||
public int getSize() { | ||
try { | ||
return Math.toIntExact(dataCache.estimatedSize()); | ||
} catch (ArithmeticException e) { | ||
return Integer.MAX_VALUE; | ||
} | ||
} | ||
|
||
@Override | ||
public ReadWriteLock getReadWriteLock() { | ||
return null; | ||
} | ||
|
||
@Override | ||
public int hashCode() { | ||
return Objects.hash(dataCache, getId()); | ||
} | ||
|
||
@Override | ||
public boolean equals(Object o) { | ||
if (this == o) return true; | ||
if (!(o instanceof DatabaseCache)) return false; | ||
DatabaseCache that = (DatabaseCache) o; | ||
return dataCache.equals(that.dataCache) && | ||
getId().equals(that.getId()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16 changes: 16 additions & 0 deletions
16
src/main/java/com/nike/cerberus/server/config/guice/StaticInjector.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package com.nike.cerberus.server.config.guice; | ||
|
||
import com.google.inject.Inject; | ||
import com.google.inject.Injector; | ||
|
||
/** | ||
* This is needed for Classes created outside our normal process that can be created with Guice such as MyBatis caches. | ||
*/ | ||
public class StaticInjector { | ||
|
||
@Inject static Injector injector; | ||
|
||
public static Injector getInstance() { | ||
return injector; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.