Ehcache is another cache solution that many people forget about. Yes, Ehcache has become a bit of a wane in the Redis era, but it is important to know about Ehcache. In some cases, we still use Ehcache.

Today Songo will talk to you about using Ehcache in Spring Boot. We believe that after reading this article, you will have a deeper understanding of the second solution in Spring Boot2 tutorial (26).

Ehcache is also one of the best caching solutions in the Java world. The name of Ehcache is very interesting. Spring Boot also supports Ehcache. This support is primarily implemented through Spring Cache.

Spring Cache can integrate Redis and Ehcache, but the two caching solutions are similar in terms of configuration and usage, similar to JDBC and database-driven relationships. After the previous configuration is complete, the API used in the following steps is the same.

Compared to Spring Cache + Redis, Spring Cache + Ehcache is mainly configured differently, and the specific usage is exactly the same. Let’s take a look at how to use it.

Project creation

First, create a Spring Boot project that introduces Cache dependencies:

After the project is created, the dependency of Ehcache is introduced. Ehcache currently has two versions:

Here we take the second, in the pom.xml file, to introduce the Ehcache dependency:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.6</version>
    </dependency>
</dependencies>
Copy the code

Example Add Ehcache configuration

Add the ehcache configuration file ehcache. XML to the resources directory as follows:

<ehcache>
    <diskStore path="java.io.tmpdir/shiro-spring-sample"/>
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
    />
    <cache name="user"
            maxElementsInMemory="10000"
            eternal="true"
            overflowToDisk="true"
            diskPersistent="true"
            diskExpiryThreadIntervalSeconds="600"/>
</ehcache>
Copy the code

Configuration meanings:

  1. Name: indicates the cache name.
  2. MaxElementsInMemory: Maximum number of caches.
  3. Eternal: Whether the object is permanent. Once it is set, timeout will not work.
  4. TimeToIdleSeconds: Sets the time (in seconds) that the object is allowed to remain idle before becoming invalid. Used only when eternal=false object is not permanently valid, optional property, default is 0, that is infinite idle time.
  5. TimeToLiveSeconds: Sets the time (in seconds) that the object is allowed to live before becoming invalid. The maximum time is between the creation time and the expiration time. Used only when eternal=false object is not permanently valid, the default is 0., that is, the object lifetime is infinite.
  6. OverflowToDisk: Ehcache writes objects to disk when the number of objects in memory reaches maxElementsInMemory.
  7. DiskSpoolBufferSizeMB: This parameter sets the size of the DiskStore cache. The default is 30MB. Each Cache should have its own buffer.
  8. MaxElementsOnDisk: indicates the maximum number of caches on a hard disk.
  9. DiskPersistent: Specifies whether to cache data during vm restart.
  10. DiskExpiryThreadIntervalSeconds: disk failure thread running time interval, the default is 120 seconds.
  11. MemoryStoreEvictionPolicy: when maxElementsInMemory limit is reached, Ehcache will be based on the specified strategies to clear the memory. The default policy is LRU (least recently used). You can set it to FIFO (First in, first out) or LFU (less used).
  12. ClearOnFlush: Specifies whether to flush the maximum memory.
  13. DiskStore represents the disk directory that is temporarily cached.

Pay attention to

By default, this file name is fixed and must be called ehcache.xml. If you must change the name, specify the configuration file name explicitly in application.properties as follows:

spring.cache.ehcache.config=classpath:aaa.xml
Copy the code

Open the cache

The way to EnableCaching is the same as that in Redis. Add the @enablecaching dependency as follows:

@SpringBootApplication
@EnableCaching
public class EhcacheApplication {
    public static void main(String[] args) { SpringApplication.run(EhcacheApplication.class, args); }}Copy the code

In fact, at this point, Ehcache configuration is complete, and the following usage is exactly the same as in songo’s previous article on Redis. But here songo is going to show you.

Use the cache

Here are some of the core annotations used in caching.

@CacheConfig

This annotation is used on a class to describe the cache name used by all the methods in the class. It is also possible to configure the name on a specific cache annotation without using this annotation, as shown in the following example:

@Service
@CacheConfig(cacheNames = "user")
public class UserService {}Copy the code

@Cacheable

This annotation is usually added to a query method to indicate that the return value of a method is cached. By default, the cached key is the method parameter and the cached value is the method return value. Example code is as follows:

@Cacheable(key = "#id")
public User getUserById(Integer id,String username) {
    System.out.println("getUserById");
    return getUserFromDBById(id);
}
Copy the code

By default, multiple parameters are used for the key when there are multiple parameters. If only one of these parameters is required for the key, you can specify the key attribute in the @cacheable annotation. If you have complex requirements for keys, you can customize the keyGenerator. Of course, Spring Cache provides root objects that can achieve some complex effects without defining keyGenerator. Root objects have the following properties:

You can also customize keys using keyGenerator as follows:

@Component
public class MyKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object target, Method method, Object... params) {
        returnmethod.getName()+Arrays.toString(params); }}Copy the code

Then use the keyGenerator on the method:

@Cacheable(keyGenerator = "myKeyGenerator")
public User getUserById(Long id) {
    User user = new User();
    user.setId(id);
    user.setUsername("lisi");
    System.out.println(user);
    return user;
}
Copy the code

@CachePut

When data in the database is updated, the data in the cache is also updated. Using this annotation, you can automatically update the return value of the method to an existing key, as shown in the following code:

@CachePut(key = "#user.id")
public User updateUserById(User user) {
    return user;
}
Copy the code

@CacheEvict

This annotation is usually added to the delete method. When data in the database is deleted, the relevant cache data is automatically deleted. This annotation can also be configured to delete according to certain conditions (condition attribute) or to delete all caches (allEntries attribute).

@CacheEvict(a)public void deleteUserById(Integer id) {
    // Delete from the database
}
Copy the code

conclusion

This article mainly introduces the use of Spring Boot integrated Ehcache, in fact, it is the use of Spring Cache. After reading this article, you will have a better understanding of the Redis + Spring Cache.

This article I have uploaded to GitHub, welcome everyone star: github.com/lenve/javab…

If you have any questions about this article, please leave a comment.

Scan code to pay attention to Songko, the public account background reply 2TB, get songko exclusive super 2TB free Java learning dry goods