Redis is used as the cache in the Spring boot project.
Create a spring boot maven project to add dependencies in Pom.xml
<Dependency> <groupId>Org.springframework.boot</groupId> <Artifactid>Spring-boot-starter-web</Artifactid> <version>1.5.3.RELEASE</version> </Dependency> <Dependency> <groupId>Org.springframework.boot</groupId> <Artifactid>Spring-boot-starter-redis</Artifactid> <version>1.3.8.RELEASE</version> </Dependency>
adding configurations in Application.properties
server.port:9000 #服务启动的端口
spring.redis.database=0 #redis数据库的索引, default is 0spring.redis.host=192.168.133.130# Spring.redis.password=spring.redis.port=6379spring.redis.pool.max-idle=8 #最大空闲链接数 Spring.redis.pool.min-idle=0 #最小空闲连接数spring.redis.pool.max-active=8 #连接池最大连接数, negative indicates no maximum number of connections Spring.redis.pool.max-wait=-1 #连接池最大阻塞等待时间, negative indicates no #spring. Redis.sentinel.master= #主节点# Spring.redis.sentinel.nodes=
spring.data.mongodb.host=192.168.133.130spring.data.mongodb.port=27017spring.data.mongodb.database= Fzk
adding annotations to the Startup class
@SpringBootApplication@EnableCaching
Public class Main { publicstaticvoidthrows Exception { Springapplication.run (Main. class , args);} }
@EnableCaching will be @ Cacheable
, @ and @ for each CachePut
beanCacheEvict修饰的public方法进行缓存操作。
Usage of the cache
@Cacheable (value = "Test", key = "' User_ '. Concat (#root. args[0])") public user GetUser ( String userId) { System.out.println ("in GetUser"); New User (); User.setid (userId); User.setpassword ("passwd"); User.setusername ("username"); return user; }
This method, when the UserID is identical, executes the method the first time it is called, and the data in the cache is read each time it is called.
Description of the cached annotations:
@Cacheable
This annotation, each time first check whether the method is executed, in the cache database to see if the key is equal, if found, read from the cache, there is no match then execute the method, the result is cached.
The cache is stored through Key-value, and value or Cachenames must be specified (value is the alias of the Cachenames), specifying multiple value (value = {"Value1", "value2"}) if no key is specified, Spring will provide a default keygenerator, which generates a key based on the parameters, Keygenerator If the method does not have a parameter that returns KEYGENERATOR.EMPTY, if there is a parameter that returns this instance, if there are multiple arguments, the Simplekey that contains the parameters are returned. You can specify keygenerator by inheriting Cachingconfigurersupport, adding @configuration annotations to the class. You can also specify the key yourself as above, and you need to know the spel expression.
In the case of multithreading, multiple threads may simultaneously enter a method that has not been cached, which causes multiple threads to execute the method again,sync= "true" will first calculate the return value of this method lock, the result is cached after the calculation is completed
@Cacheable (value= "Foos", sync= "true") public Foo executeexpensiveoperation (String ID) {...}
In some cases, you may not want to cache the results, which can be filtered by condition
@Cacheable (value= "book", condition= "#name. Length () < +") public book Findbook (String name)
The above #root represents the return value, some other available parameters (from the spring website)
@CachePut
The method is executed each time and the result is cached. Usage is consistent with @cacheable usage.
@CacheEvict
Used to empty the cache, you can specify key, value, condition, and the usage is the same as described above. Key and condition can be null if empty, indicating the default policy.
@CacheEvict (value= "Books", allentries=True, Beforeinvocation=true)publicvoid Loadbooks (InputStream Batch)
Allentries=true indicates that all caches under books are emptied, and by default false,beforeinvocation=true indicates whether the cache is emptied before the method executes, and defaults to false.
@Caching
Can contain the three annotations described above, corresponding to Key-value (cachable=[@Cacheable], put=[@CachePut], evict=[@CacheEvict])
@Caching (evict = {@CacheEvict ("primary"), @CacheEvict (cachenames= "secondary", key= "#p0")}) Public Book Importbooks (String deposit, date date)
@CacheConfig
is a class-level annotation
@CacheConfig ("Books")publicclassimplements bookrepository { @ cacheable Public book Findbook (ISBN ISBN) {...}}
The cache for each method under such a class is books, and you can specify custom Keygenerator andCacheManager。
Custom Cache annotations
Implement custom annotations directly as a meta by using the above annotations
@Retention (retentionpolicy.runtime) @Target ({Elementtype.method}) @Cacheable (Value= "Books", key= "#isbn" ) public @Interface slowservice {}
So we can use @slowservice directly as annotations.
@SlowService Public Boolean boolean includeused)
Same as the following annotation features
@Cacheable (cachenames= "Books", key= "#isbn")publicbooleanboolean includeused)
Spring Boot integrated Redis cache