下面列出了怎么用org.springframework.boot.convert.DurationStyle的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected RedisCache createRedisCache(String name, @Nullable RedisCacheConfiguration cacheConfig) {
if (StringUtil.isBlank(name) || !name.contains(StringPool.HASH)) {
return super.createRedisCache(name, cacheConfig);
}
String[] cacheArray = name.split(StringPool.HASH);
if (cacheArray.length < 2) {
return super.createRedisCache(name, cacheConfig);
}
String cacheName = cacheArray[0];
if (cacheConfig != null) {
// 转换时间,支持时间单位例如:300ms,第二个参数是默认单位
Duration duration = DurationStyle.detectAndParse(cacheArray[1], ChronoUnit.SECONDS);
cacheConfig = cacheConfig.entryTtl(duration);
}
return super.createRedisCache(cacheName, cacheConfig);
}
/**
* 从 cache name 中解析 ttl,例如: user:test#300ms,不带单位默认为 s 秒
*
* @param cacheName 缓存名
* @return 超时时间
*/
public static long getTTLFormCacheName(String cacheName) {
String[] cacheArray = cacheName.split(StringPool.HASH);
if (cacheArray.length < 2) {
return -1L;
}
Duration duration = DurationStyle.detectAndParse(cacheArray[1], ChronoUnit.SECONDS);
return duration.toMillis();
}
public void setExpirationPerCache(Map<String, String> expirationPerCache) {
if (expirationPerCache != null) {
expirationPerCache.forEach((cacheName, cacheExpiration) -> {
Duration exp = DurationStyle.detect(cacheExpiration).parse(cacheExpiration, ChronoUnit.SECONDS);
validateExpiration(exp);
this.expirationPerCache.put(cacheName, exp);
});
}
}
private boolean checkType(String type, String text, ClassLoader cl) throws IllegalArgumentException {
Class<?> clazz = ClassUtils.resolveClassName(type, cl);
if (clazz != null) {
try {
parser.parseType(text, clazz);
} catch (Exception e1) {
if (clazz.isEnum()) {
// generate and try relaxed variants of value
for (String relaxedName : new RelaxedNames(text)) {
try {
parser.parseType(relaxedName, clazz);
return true;
} catch (Exception e2) {
// try another variant
}
if (canceled) {
break;
}
}
return false;
} else {
try {
// handle a few specific cases where no direct constructor from string or converter exist
switch (type) {
case "java.nio.file.Path":
Paths.get(text);
return true;
case "java.util.Locale":
LocaleUtils.toLocale(text);
return true;
case "java.time.Duration":
DurationStyle.detectAndParse(text);
return true;
case "org.springframework.util.unit.DataSize":
DataSize.parse(text);
return true;
case "java.lang.Class":
cl.loadClass(text);
return true;
default:
return false;
}
} catch (Exception e3) {
return false;
}
}
}
}
// unresolvable/unknown class, assume user knows what is doing
return true;
}
private void resolveTimeout(Environment environment) {
String providedTimeout = environment.getProperty(SERVICE_DISCOVERY_TIMEOUT);
if (providedTimeout != null) {
timeout = DurationStyle.detectAndParse(providedTimeout);
}
}