This is the 13th day of my participation in Gwen Challenge.
Today, we use Caffeine, the most powerful Java in-heap caching framework ever, for application integration based on the Spring Boot framework. Caffeine is a high performance, near optimal Caching Library, yes, at all! Vaunted as a high-performance, near-optimal cache library.
First, why it?
Why Caffeine is so confident, is that Google has implemented a fairly comprehensive upgrade to GuavaCache with the help of Java 8. Upgraded what content, the content is a lot, not a repeat, only underlined. It provides a richer cache expiration strategy, especially based on the Google engineer Window TinyLfu recycling strategy, which provides a near-optimal hit ratio. Because of its performance, Spring 5 has ditched Guava and embraced Caffeine.
Ii. Engineering practice
As the saying goes, learn how to use tools before you learn how to create them. This article will not go into the depth of Caffeine, but have a chance to write another in-depth article. Let’s use it simply based on Spring Boot + Java 8.
2.1 the dependencies
There are only two dependencies that need to be introduced, namely spring-boot-starter-cache and Caffeine. The version number of caffeine needs to be configured according to the project needs.
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> < artifactId > spring - the boot - starter - cache < / artifactId > < version > 2.3.8. RELEASE < / version > < / dependency > < the dependency > < the groupId > com. Making. Ben - manes. Caffeine < / groupId > < artifactId > caffeine < / artifactId > < version > 2.8.8 < / version > </dependency> </dependencies>Copy the code
2.2 Development Process
Develop automatic assembly based on SpringBoot.
Start by writing a configuration file OrderCaffeineProperties
@ConfigurationProperties(prefix = "me.caffeine.order")
@Getter
@Setter
public class OrderCaffeineProperties {
private String name = "order";
private int initSize = 10;
private int maxSize = 1000;
private Duration expireTime = Duration.ofMinutes(10);
}
Copy the code
This configuration file is relatively simple. It is mainly used to configure the initialization size, maximum storage range, and expiration time of the cache for initialization.
Next is the configuration class OrderCaffeineAutoConfigure
@EnableConfigurationProperties(OrderCaffeineProperties.class) @Configuration public class OrderCaffeineAutoConfigure { @Bean @ConditionalOnMissingBean( name = {"orderCache"} ) public Cache<Long, BigDecimal> orderCache(OrderCaffeineProperties properties) { return Caffeine.newBuilder() .initialCapacity(properties.getInitSize()) .maximumSize(properties.getMaxSize()) .expireAfterWrite(properties.getExpireTime().getSeconds(), TimeUnit.SECONDS) .build(); }}Copy the code
In the configuration class, a simple cache bean is instantiated according to the parameters of the configuration file and entrusted to container management.
Then configure the autowire files in the Resources/META-INF directory of the project. Add a spring.factories file.
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
me.stone.training.platform.spring4all.caffeine.autoconfigure.OrderCaffeineAutoConfigure
Copy the code
2.3 Test Process
This test stole a lazy, directly in the test directory to create a new application Launcher class, watch the cache failure process.
@SpringBootApplication
@Slf4j
public class Launcher {
@SneakyThrows
public static void main(String[] args) {
final ConfigurableApplicationContext ctx = SpringApplication.run(Launcher.class, args);
final Cache<Long, BigDecimal> orderCache = (Cache<Long, BigDecimal>) ctx.getBean("orderCache", new TypeReference<Cache<Long, BigDecimal>>() {});
orderCache.put(1L,BigDecimal.valueOf(100));
orderCache.put(2L,BigDecimal.valueOf(200));
log.info("start...");
orderCache.asMap().forEach((k,v)-> log.info("key is {},and value is {}",k,v));
TimeUnit.SECONDS.sleep(30);
log.info("sleep 30s");
orderCache.asMap().forEach((k,v)-> log.info("key is {},and value is {}",k,v));
TimeUnit.SECONDS.sleep(40);
log.info("sleep 70s");
orderCache.asMap().forEach((k,v)-> log.info(" key is {},and value is {}",k,v));
ctx.close();
}
}
Copy the code
The project configuration file application.yml contains the following contents
me:
caffeine:
order:
expire-time: 70s
init-size: 10
max-size: 1000
name: order
Copy the code
The configuration content is that the cache is invalid 70s after establishment. The initial size of the cache is 10 and the maximum range is 1000.
After starting the application class, the result of execution is as follows
As expected, since the configured cache was 70s, the cache was not invalidated 30 seconds after the cache was set up, so the contents of the cache were still there. 70s after the cache is set up, the cache has been invalidated, so the contents of the cache have been cleared.
2.4 Source Code address
Attach a lot the source address of the training. The platform. Spring4all. Caffeine