对于未来的读者,这里是我曾经使用 Spring Boot@ConfigurationProperties
配置 Caffeine Cache 的代码:
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
/**
* Base class for configuration of a Caffeine {@link Cache}
*/
public class CaffeineCacheProperties {
private Integer maximumSize;
// TODO: Add additional properties + getters and setters.
public Integer getMaximumSize() {
return maximumSize;
}
public void setMaximumSize(final Integer maximumSize) {
this.maximumSize = maximumSize;
}
public Caffeine initializeCacheBuilder() {
Caffeine cacheBuilder = Caffeine.newBuilder();
if (maximumSize != null) {
cacheBuilder.maximumSize(maximumSize);
}
// TODO: Configure additional properties.
return cacheBuilder;
}
}
.
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The cache {@link Configuration} class.
*/
@Configuration
public class CacheConfig {
@Bean
@ConfigurationProperties("cache.customer")
public CaffeineCacheProperties customerCacheProperties() {
return new CacheProperties();
}
@Bean
public Cache<String, Customer> customerCache() {
return customerCacheProperties().initializeCacheBuilder().build();
}
// TODO: Add other caches.
}
然后添加一个应用程序属性,如:
cache.customer.maximum-size: 1000