Home  >  Article  >  Database  >  Introduction to the method of integrating Redis cache with SpringBoot

Introduction to the method of integrating Redis cache with SpringBoot

尚
forward
2020-06-20 16:30:284578browse

Introduction to the method of integrating Redis cache with SpringBoot

How SpringBoot integrates Redis cache:

1. Introduce cache dependency

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
     <version>2.1.5.RELEASE</version>
</dependency>

2. Add cache configuration

in application Add the following configuration to the .properties file

## Redis部分
# Redis服务器地址
spring.redis.host=${redis.host}
# Redis服务器连接端口
spring.redis.port=${redis.port}
# Redis服务器连接密码(默认为空)
spring.redis.password=${redis.password}
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=${redis.maxTotal}
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=${redis.maxIdle}
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=4
# 连接超时时间(毫秒)
spring.redis.timeout=5000

## Cache部分
#缓存的名称集合,多个采用逗号分割
spring.cache.cache-names=
#缓存的类型,官方提供了很多,这里我们填写redis
spring.cache.type=redis
#是否缓存null数据,默认是false
spring.cache.redis.cache-null-values=false
#redis中缓存超时的时间,默认60000ms
spring.cache.redis.time-to-live=60000
#缓存数据key是否使用前缀,默认是true
spring.cache.redis.use-key-prefix=true
#缓存数据key的前缀,在上面的配置为true时有效,
spring.cache.redis.key-prefix=

3. Add the enable caching annotation EnableCaching

@EnableCaching
public class WebApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}

4. Add the caching annotation

@Cacheable

The annotation’s function It indicates that the return value of this method will be cached;

You need to pay attention to condition and unless, they are both conditional judgment parameters:

  • condition: judge before calling the method , so the result value of the method cannot be used as a judgment condition;

  • unless: judgment is made after the method is called. At this time, the method return value can be obtained as a judgment condition.

So the operation that relies on the method return value as whether to cache must use the unless parameter instead of condition

@CachePut

Update the method return value Current cache

@CacheEvict

Expire (clear) the current cache

For more related knowledge, please pay attention to redis introductory tutorialcolumn

The above is the detailed content of Introduction to the method of integrating Redis cache with SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete