Spring boot configuration JVM cache

Posted by micbox on Thu, 14 Nov 2019 16:06:48 +0100

  • Cache classification: cache is divided into memory cache and JVM cache
    Memory cache, such as redis
    JVM cache is only used in java, and a single JVM is valid
  • Cache usage scenarios
    Reduce database access pressure
  1. Create the springboot project < this article configures the JVM cache >
  2. Add cache dependency in pom.xml
    ​
    <!-- springboot Cache dependency -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    
    ​

     

  3. Create the ehcache.xml configuration file in the resources directory
    <?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">
    	<diskStore path="java.io.tmpdir/Tmp_EhCache" />
    
    <!-- name:Cache name.  
         maxElementsInMemory: Maximum number of caches.  
         eternal:Whether the object is permanently valid, once it is set, timeout It will not work.  
         timeToIdleSeconds: Sets the allowed idle time (in seconds) of the object before expiration. Only when eternal=false Object is not used when it is permanently valid. Optional property. The default value is 0, which means infinite idle time.  
         timeToLiveSeconds: Sets the time (in seconds) that an object is allowed to live before it expires. The maximum time is between creation time and expiration time. Only when eternal=false Used when the object is not permanently valid, the default is 0.,That is, the life time of the object is infinite.  
         overflowToDisk: When the number of objects in memory reaches maxElementsInMemory At that time, Ehcache Write objects to disk.  
         diskSpoolBufferSizeMB: This parameter setting DiskStore(Disk cache). The default is 30. MB. each Cache Each should have its own buffer.  
         maxElementsOnDisk: Maximum number of hard disk cache.  
         diskPersistent: Whether to cache virtual machine restart data Whether the disk store persists between restarts of the Virtual Machine. The default value is false.  
         diskExpiryThreadIntervalSeconds: Disk failure thread run time interval, default is 120 seconds.  
         memoryStoreEvictionPolicy: When reach maxElementsInMemory When limiting, Ehcache The memory will be cleaned according to the specified policy. The default policy is LRU(Least recently used). You can set to FIFO(First in, first out) or LFU(Less use).  
         clearOnFlush: Clear when the maximum amount of memory
     -->
    	<!-- Default configuration -->
    	<defaultCache maxElementsInMemory="5000" eternal="false"
    		timeToIdleSeconds="120" timeToLiveSeconds="120"
    		memoryStoreEvictionPolicy="LRU" overflowToDisk="false" />
    
    	<cache name="baseCache" maxElementsInMemory="10000"
    		maxElementsOnDisk="100000" />
    
    </ehcache>
    

     

  4. Add the enable caching annotation @ EnableCaching / / to the App startup class to enable caching annotation
    package com.trip;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
    import org.springframework.cache.annotation.EnableCaching;
    
    @SpringBootApplication
    @EnableCaching // Enable cache annotation
    public class App {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		SpringApplication.run(App.class, args);
    	}
    
    }

     

  5. Create user related classes and business logic layers
    // Control layer
    @Controller
    public class IndexController {
    	
    	@Autowired
    	private UserService userService;
    	
    	@GetMapping("/obtain")
    	@ResponseBody
    	public Object obtain(){
    		return userService.getUserMapper().findByPhone("17688796355");
    	}
    
    }
    // Business logic layer
    package com.trip.ehCache.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import com.trip.ehCache.dao.UserMapper;
    
    
    @Service
    @Transactional
    public class UserService {
    	@Autowired
    	private UserMapper userMapper;
    	
    	public UserMapper getUserMapper() {
    		return userMapper;
    	}
    	
    }
    // Data access layer
    import org.springframework.cache.annotation.CacheConfig;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
    import com.trip.ehCache.entity.User;
    
    @CacheConfig(cacheNames = "baseCache") // Configure ehcache.xml annotation, baseCache is the name defined for the configuration file
    public interface UserMapper extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User>{
    
    	@Cacheable // This query uses cached annotations
    	User findByPhone(String phone);
    	
    }

     

  6. Test url http://localhost:8080/obtain
  7. Delete the data of the database, and the page still displays
  8. Delete cache
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.CacheManager;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import com.trip.ehCache.service.UserService;
    
    @Controller
    public class IndexController {
    	
    	@Autowired
    	private UserService userService;
    	
    	@Autowired
    	private CacheManager cacheManager;
    	
    	/**
    	 * Add cache
    	 * @return
    	 */
    	@GetMapping("/obtain")
    	@ResponseBody
    	public Object obtain(){
    		return userService.getUserMapper().findByPhone("17688796355");
    	}
    	
    	/**
    	 * Delete cache
    	 * @return
    	 */
    	@GetMapping("/delete")
    	@ResponseBody
    	public Object delete(){
    		cacheManager.getCache("baseCache").clear();
    		return "Delete cache";
    	}
    
    }
  9.  

Topics: Ehcache jvm xml Java