Spring Boot series: Spring Boot integrates Spring Cache and uses EhCache

In the previous chapter, I explained Spring Boot integrates Spring Cache Spring Cache has completed the implementation of various caches, including EhCache, RedisCache, ConcurrentMapCache, etc.

In this section, let's take a look at Spring Cache using EhCache.

I. demonstration of EhCache

EhCache is a pure Java in-process Cache framework, which has the characteristics of fast, lean and so on. The default Cache in Hibernate is the EhCache used.

An example of this chapter is in Spring Boot integrates Spring Cache Based on the source code of the transformation. Source address: https://github.com/imyanger/springboot-project/tree/master/p20-springboot-cache

Using EhCache as cache, we first introduce related dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--ehcache rely on-->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Then create ehcache.xml, EhCache's configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

    <!--
        Disk storage: transfer the temporarily unused objects in the cache to the hard disk, similar to the virtual memory of Windows system
        Path: Specifies the path to store objects on the hard disk
        path can be configured in the following directories:
        user.home (user's home directory)
        user.dir (user's current working directory)
        java.io.tmpdir (default temporary directory)
        ehcache.disk.store.dir (ehcache configuration directory)
        Absolute path (e.g. d:\ehcache)
        View path method: String tmpDir = System.getProperty("java.io.tmpdir");
     -->
    <diskStore path="java.io.tmpdir" />

    <!--
        defaultCache: the default cache configuration information. All objects are processed according to this configuration item unless otherwise specified.
        maxElementsInMemory: set the upper limit of cache and how many record objects can be stored at most
        Oracle: indicates whether the object will never expire (if true is specified, the following two configurations need to be 0 indefinitely)
        timeToIdleSeconds: maximum daze time / second
        timeToLiveSeconds: maximum lifetime / sec
        Overflow todisk: whether to allow objects to be written to disk
        Note: the following configuration is valid for 600 seconds (10 minutes) since cache establishment.
        If the cache is not accessed for 120 seconds (2 minutes) in a valid 600 second (10 minute) period, the cache is invalidated.
        Even if there is an interview, it will only survive for 600 seconds.
     -->
    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600"
                  timeToLiveSeconds="600" overflowToDisk="true" />

    <cache name="cache" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120"
           timeToLiveSeconds="600" overflowToDisk="true" />

</ehcache>

Then in the spring boot configuration file, indicate the cache type and declare the location of the Ehcache configuration file.

server:
  port: 10900

spring:
  profiles:
    active: dev
  cache:
    type: ehcache
    ehcache:
      config: classpath:/ehcache.xml

So you can start using Ehcache to test the code against the Spring Boot integrates Spring Cache Agreement.

SpringBoot startup class, @ EnableCaching enables Spring Cache caching.

@EnableCaching
@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        String tmpDir = System.getProperty("java.io.tmpdir");
        System.out.println("Temporary path:" + tmpDir);
        SpringApplication.run(SpringbootApplication.class, args);
    }

}

The CacheApi interface calls the class, which is convenient to call for testing.

@RestController
@RequestMapping("cache")
public class CacheApi {

    @Autowired
    private CacheService cacheService;

    @GetMapping("get")
    public User  get(@RequestParam int id){
        return cacheService.get(id);
    }

    @PostMapping("set")
    public User  set(@RequestParam int id, @RequestParam String code, @RequestParam String name){
        User u = new User(code, name);
        return cacheService.set(id, u);
    }

    @DeleteMapping("del")
    public void  del(@RequestParam int id){
        cacheService.del(id);
    }
    
}

CacheService cache business processing class, add cache, update cache and delete.

@Slf4j
@Service
public class CacheService {

    private Map<Integer, User> dataMap = new HashMap <Integer, User>(){
        {
            for (int i = 1; i < 100 ; i++) {
                User u = new User("code" + i, "name" + i);
                put(i, u);
            }
        }
     };

    // get data
    @Cacheable(value = "cache", key = "'user:' + #id")
    public User get(int id){
        log.info("adopt id{}Query acquisition", id);
        return dataMap.get(id);
    }

    // Update data
    @CachePut(value = "cache", key = "'user:' + #id")
    public User set(int id, User u){
        log.info("To update id{}data", id);
        dataMap.put(id, u);
        return u;
     }

    //Delete data
    @CacheEvict(value = "cache", key = "'user:' + #id")
    public void del(int id){
        log.info("delete id{}data", id);
        dataMap.remove(id);
    }
    
}

Source address: https://github.com/imyanger/springboot-project/tree/master/p22-springboot-cache-ehcache

Tags: Programming Ehcache Spring Java SpringBoot

Posted on Wed, 23 Oct 2019 10:48:57 -0700 by amiller099