You can use memory as a cache, or you can use Redis as a cache, and the disadvantage of memory is that multiple instances of the cluster are not synchronized
1, adding dependencies
< Dependency > < groupId >org.springframework.boot</groupId> < Artifactid>spring-boot-starter-data-redis</artifactid> </dependency>
2. Configure the Redis data source in the configuration file
spring.cache.redis.time-to-live:3600s # Default, set a time to indicate expiration time Redis.host=localhost # ipredis.port=6379 # Port Redis.jedis.pool.max-active=5 # Connection Pool redis.jedis.pool.max-idle=10redis.jedis.pool.max-wait=10000
3, Start class add @EnableCaching annotations
4, add @Cacheable/@CacheEvict/@CachePut annotations on the method or add @CacheConfig annotations on the class
@Cacheable get the cache (without running the method), if you do not get the Run method and put the value in the cache
@CacheEvict Delete the cache (this method executes every time and then goes through the return value of the method and deletes it)
@CachePut Update the cache (this method is also executed every time, through the method return value to check, if there is an update, no add)
@CacheConfig This is written on the class to simplify the above 3 annotations
Example:
Example 1: @Cacheable (cachenames= "User", key= "#id") PublicUser Getuserbyid (intID) {} Example 2: @CachePut (Cachenames= "User", key= "#user. ID") Publicuser Updateuserbyid (user user) {} Example 3: @CacheEvict (cachenames= "User") PublicUser Deleteuserbyid (intID) {}//If the parameter is a basic type, then the key defaults to him, such as example 3 does not write key, in fact, and Example 1 is the same Example 4: @CacheConfig ("User") Public classuserservice{@Cacheable PublicUser Getuserbyid (intID) {} @CachePut (key= "#user. ID") Publicuser Updateuserbyid (user user) {}}
Note: Similar to asynchronous execution, only external calls take effect
Springboot Redis Cache