spring boot integrated redis usage tutorial

Tip: This is a simple, easy-to-read spring boot integrated redis tutorial. Before using it again, please download the redis service in your computer first.

Table of contents

1. What is redis

2. The project integrates redis-related dependencies (the default lettuce used here is used as the redis client, and you can choose to introduce jedis)

3. Add redis configuration class

4. How to use redis cache

4.1 Spring Boot cache annotation

 4.2 Start redis service

4.2 Implementation

Summarize


1. What is redis

2. The project integrates redis-related dependencies (the default lettuce used here is used as the redis client, and you can choose to introduce jedis)

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--spring2.X集成redis所需common-pool2-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.0</version>
        </dependency>

3. Add redis configuration class

@Configuration //配置类
@EnableCaching //开启缓存
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new
                Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config =
                RedisCacheConfiguration.defaultCacheConfig()
                        .entryTtl(Duration.ofSeconds(600)) //设置缓存存在的时间 600s
                        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                        .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }


}

4. How to use redis cache

First of all, it is necessary to clarify where the cache needs to be used in a project. Generally speaking, the front-end users have a large number of visits. And because the foreground data changes are not very frequent, more query operations are involved. Therefore, it is necessary for us to cache front-end related (such as home page) data in the redis cache to reduce database pressure and improve access speed.

4.1 Spring Boot cache annotation

(1) Cache @Cacheable
caches the returned results according to the method. When the next request is made, if the cache exists, the cached data is directly read and returned; if the cache does not
exist, the method is executed and the returned result is stored in the cache. Generally used on 查询方法the Internet.
View the source code, the property values ​​are as follows:

(2) Cache @CachePut

The method marked with this annotation will be executed every time, and the result will be stored in the specified cache. Other methods can read cached data directly from the response cache
without having to query the database. Generally used on 新增方法the Internet.

(3) Cache @CacheEvict

The method using this annotation flag will clear the specified cache. Generally used to 更新或者删除方法view
the source code, the attribute values ​​​​are as follows:

 4.2 Start redis service

Start the redis service on your computer

4.3 Implementation

 (1) Add redis configuration in the yml file

spring: 
  redis: 
    host: 192.168.101.132 #IP address where redis is located 
    port: 6379 
    password: root #Password 
    connect-timeout: 1800000 #Connection redis timeout time, (the expiration time is configured in the config class) database: 0 #lettuce client is used to connect to redis lettuce: pool: max-active: 20 #lettuce 
    maximum 
    Number 
    of 
      connections 
        : the "maximum number of connections" that can be established at the same time max-wait: 1 #lettuce Maximum 
        waiting time for obtaining Collection from the connection pool: unit ms 
        max-idle: 5 #Maximum idle number: When the number of idle connections is greater than maxIdle, it will be recycled 
        min-idle: 0 #Minimum idle number: When it is lower than minIdle, a new connection will be created

Because the query is first checked from the cache, and if the data is modified, in order to ensure the final consistency of the data. Here you choose to add @CacheEvict annotations to methods such as modification, deletion, and addition. When the above methods are executed, the cache is directly deleted, and then the data is retrieved from the database and added to the cache.

like

Query related methods:

    @Cacheable(value = "banner", key = "'selectIndexList'")
    @Override
    public List<CrmBanner> selectIndexList() {
        List<CrmBanner> list = baseMapper.selectList(new
        QueryWrapper<CrmBanner>().orderByDesc("sort"));
        return list;
    }

Modify, delete, add related methods:

    //CacheEvict用于更新或删除,allEntries属性清楚缓存
    @CacheEvict(value = "banner", allEntries=true)
    @Override
    public void updateBannerById(CrmBanner banner) {
   		 baseMapper.updateById(banner);
    }

Finally, test it.


Summarize

So far, a simple redis usage is complete

Guess you like

Origin blog.csdn.net/weixin_58403235/article/details/129895603