Springboot Redis Cache

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.