Docker install Redis (skip this step if already installed)

1. Pull Redis image (latest version by default)

docker pull redis
Copy the code

If the download is slow, you are advised to configure Ali Cloud image

View Ali Cloud image: Ali Cloud official website –> Product –> Search for Container image service –> Management Console

The mirror accelerator below the left sidebar:

Click on it and you can see an acceleration address and how to use it below:

Copy the braces and their contents into /etc/docker-daemon. json:

vim /etc/docker/daemon.json
Copy the code

After reloading the Daemon file and docker, the image is added successfully

systemctl daemon-reload

systemctl restart docker
Copy the code

2. Check whether the Redis image is successfully installed

docker images
Copy the code

3. Run Redis

docker run -d -p 6379:6379 --name myredis redis
Copy the code

4. Check whether the command is successfully executed

docker ps
Copy the code

Use Redis quickly

1. Import Redis dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Copy the code

2. Add the configuration file

# Redis database index (default 0)
spring.redis.database=0  
# Redis server address (default localhost)
spring.redis.host=localhost
# Redis server connection port (default: 6379)
spring.redis.port=6379  
# Redis server connection password (default null)
spring.redis.password=
The maximum number of connections in the pool (using negative values to indicate no limit) defaults to 8
spring.redis.lettuce.pool.max-active=8
The maximum connection pool blocking wait time (negative value indicates no limit) defaults to -1
spring.redis.lettuce.pool.max-wait=- 1
The maximum number of free connections in the connection pool defaults to 8
spring.redis.lettuce.pool.max-idle=8
The minimum free connection in the connection pool defaults to 0
spring.redis.lettuce.pool.min-idle=0
Copy the code

Add the Redis configuration class

Customize a RedisCacheManager

@Configuration
public class MyRedisConfig {
    @Bean
    public RedisCacheManager defaultRedisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration cacheConfiguration =
                RedisCacheConfiguration.defaultCacheConfig()
                        .entryTtl(Duration.ofHours(6))   // Set the cache expiration time to 6 hours
                        .disableCachingNullValues()     // Disable caching null values and do not cache null validation
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
                                GenericJackson2JsonRedisSerializer()));     // Set the serialization mode of CacheManager value to JSON serialization
        return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfiguration).build();     // Set the default cache component}}Copy the code

4. Enable annotation-based caching @enablecaching

@EnableCaching
@SpringBootApplication
public class BlogApplication {

   public static void main(String[] args) { SpringApplication.run(BlogApplication.class, args); }}Copy the code

5. Use the @cacheable annotation for caching

@cacheable focuses on method configuration and can cache the results of a method based on its request parameters

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;
    
    @Cacheable(cacheNames = "totalBlog")
    @Override
    public Long getTotalBlogs(a) {
        returnblogMapper.getTotalBlogs(); }}Copy the code

Principle:

  1. Method is used to query the Cache (Cache component) for the name specified by cacheNames
  2. Calls the target method without finding the cache and puts the result returned by the target method into the cache
  3. If you find the cache, you just use the cache instead of going to the database to query the data

After performing the above steps, it is finished.

Pit trod: Deserialization of fetched data occurred with a cast exception

An exception occurred during deserialization when data of type Long was stored in Redis.

I’m storing Long data, so I’m storing Integer data.

This starts with customizing CacheManager……

@Configuration
public class MyRedisConfig {
    @Bean
    public RedisCacheManager defaultRedisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration cacheConfiguration =
                RedisCacheConfiguration.defaultCacheConfig()
                        .entryTtl(Duration.ofHours(6))   // Set the cache expiration time to 6 hours
                        .disableCachingNullValues()     // Disable caching null values and do not cache null validation
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
                                GenericJackson2JsonRedisSerializer()));     // Set the serialization mode of CacheManager value to JSON serialization
        return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfiguration).build();     // Set the default cache component}}Copy the code

We use the custom CacheManager, GenericJackson2JsonRedisSerializer serializer, And GenericJackson2JsonRedisSerializer deserialization of unity will cache the deserialization for Object types, and because we value is less than the Integer of. MAX_VALUE, naturally is converted to an Integer.

But we want to solve this kind of situation, only when storing data specified data type, you can use Jackson2JsonRedisSerializer:

@Bean
public RedisCacheManager longRedisCacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration cacheConfiguration =
            RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofHours(6))   // Set the cache expiration time to 6 hours
                    .disableCachingNullValues()     // Disable caching null values and do not cache null validation
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
                            Jackson2JsonRedisSerializer<Long>(Long.class)));     // Set the serialization method of CacheManager value to JSON serialization, specify our stored data as Long, when fetched will help us deserialize to Long
    return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfiguration).build();     // Set the default cache component
}
Copy the code

When there are two or more RedisCacheManager, we must annotate @primary on a RedisCacheManager to indicate that the RedisCacheManager is Primary; Of course, when using cache annotations for caching, if you need to use the specified RedisCacheManager, you can use the cacheManager attribute to specify, if not specified, the @Primary annotation RedisCacheManager is used by default

@Cacheable(cacheNames = "totalBlog",cacheManager = "longRedisCacheManager")
@Override
public Long getTotalBlogs(a) {
    return blogMapper.getTotalBlogs();
}
Copy the code