Docker installs Redis, and Spring Boot uses Redis to solve the type conversion exceptions in Redis

Dock installs Redis (if installed, please skip this step)

1. Pull Redis image (latest version by default)

docker pull redis

If the download is slow, it is recommended to configure alicloud image

View alicloud image: alicloud official website -- > products -- > search container image service -- > management console

Mirror accelerator below the left sidebar:

Click in to see an acceleration address and usage method below:

Copy the contents of braces and braces into / etc / docker / daemon JSON file:

vim /etc/docker/daemon.json

Reload the daemon file and docker to add the image successfully

systemctl daemon-reload 
systemctl restart docker

-

2. After installing the redis image, check whether the installation is successful

==========================

docker images

-

3. Run redis

docker run -d -p 6379:6379 --name myredis redis

4. Check whether the operation is successful

===============

docker ps

Quick use of Redis

1. Dependency of importing Redis

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

2. Add profile

# Redis database index (0 by default)
spring.redis.database=0  
# Redis server address (localhost by default)
spring.redis.host=localhost
# Redis server connection port (6379 by default)
spring.redis.port=6379  
# Redis server connection password (blank by default)
spring.redis.password=
# The maximum number of connections in the connection pool (negative value indicates no limit) is 8 by default
spring.redis.lettuce.pool.max-active=8
# Maximum blocking waiting time of connection pool (negative value indicates no limit) default - 1
spring.redis.lettuce.pool.max-wait=-1
# The maximum free connections in the connection pool are 8 by default
spring.redis.lettuce.pool.max-idle=8
# The minimum free connections in the connection pool are 0 by default
spring.redis.lettuce.pool.min-idle=0

3. Add 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 checks
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
                                GenericJackson2JsonRedisSerializer()));     // Set the value serialization method of CacheManager to json serialization
        return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfiguration).build();     // Set the default cache component
    }
}

4. Enable annotation based caching: @ EnableCaching

@EnableCaching
@SpringBootApplication
public class BlogApplication {

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

}

5. Cache with @ Cacheable annotation

@Cacheable is mainly used for method configuration. It can cache the results according to the request parameters of the method

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;
    
    @Cacheable(cacheNames = "totalBlog")
    @Override
    public Long getTotalBlogs() {
        return blogMapper.getTotalBlogs();
    }
}

Linux C / C + + server development high-level video learning materials + qun720209036 acquisition

The content includes C/C + +, Linux, Nginx, ZeroMQ, MySQL, Redis, MongoDB, ZK, streaming media, P2P, K8S, Docker, TCP/IP, Linux kernel, collaboration and DPDK.

Video link: C/C++Linux server development / background development - learning video

Principle:

  1. Before the method runs, first query the Cache (Cache component) and obtain it according to the name specified by cacheNames
  2. If the cache is not found, call the target method and put the returned result of the target method into the cache
  3. If you find the cache, you can directly use the cache, and you won't go to the database to query data

After performing the above steps, the use is completed.

Stepped pit: type conversion exception occurred in deserialization to get data

When storing Long type data in Redis, Integer to Long type conversion exception occurs during deserialization;

I clearly save Long type data. How can I save it and become Integer type?

This starts with customizing the 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 checks
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
                                GenericJackson2JsonRedisSerializer()));     // Set the value serialization method of CacheManager to json serialization
        return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfiguration).build();     // Set the default cache component
    }

}

When we customize the CacheManager, we use the GenericJackson2JsonRedisSerializer serializer, and the GenericJackson2JsonRedisSerializer will uniformly deserialize the cache to Object type during deserialization, because the value we save is less than Integer MAX_ Value is automatically converted to Integer.

If we want to solve this situation, we can only specify the data type when saving data. 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 checks
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
                            Jackson2JsonRedisSerializer<Long>(Long.class)));     // Set the value serialization method of CacheManager to json serialization, and specify that the data we save is of Long type. When we take it out, it will naturally help us deserialize it into Long type
    return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfiguration).build();     // Set the default cache component
}

When there are two or more rediscachemanagers, we must mark @ Primary annotation 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 it. If not specified, the RedisCacheManager marked with @ Primary annotation will be used by default

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

Tags: Database Docker Redis Back-end

Posted by asuperstar103 on Fri, 06 May 2022 23:50:35 +0300