Spring Boot 2.x Basic Tutorial: Using Centralized Cache Redis

Previously, we introduced the usage of two in-process caching, including the ConcurrentMap cache used by Spring Boot by default and the caching framework EhCache . Although EhCache can be applied to many application scenarios, because EhCache is an in-process caching framework, in cluster mode, the caches between application servers are independent, so there will be cache inconsistencies between processes of different servers . Even though EhCache provides a cache synchronization strategy in a cluster environment, synchronization still takes a certain amount of time, and short-term cache inconsistencies still exist.

In some systems and applications that require high consistency (any data change can be queried in time), EhCache can no longer be used to solve the problem. At this time, the use of centralized cache can solve the consistency of cached data. problem. Next we will learn how to use Redis to implement data caching in Spring Boot's caching support.

Try it

The realization of this article will be based on the basic project of the previous article . Let’s review the program elements in the next article:

Definition of User entity

@Entity
@Data
@NoArgsConstructor
public class User implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

User entity data access implementation (covering cache annotations)

@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {

    @Cacheable
    User findByName(String name);

}

Start to transform this project below:

The first step : pom.xmladd related dependencies:

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

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

In the early version of Spring Boot 1.x, the name of the dependency is spring-boot-starter-redis, so it is different from this in the Spring Boot 1.x basic tutorial .

Step 2 : Add configuration information to the configuration file, take local operation as an example, such as:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100ms

Regarding the configuration of the connection pool, note a few points:

  1. Redis's connection pool configuration in the 1.x version is prefixed spring.redis.poolwith Spring Boot 2.x.
  2. In the 1.x version, jedis is used as the connection pool, and in the 2.x version, lettuce is used as the connection pool
  3. The above configuration is the default value, in fact, production needs to be further modified according to the deployment situation and business requirements.

Let's try the unit test again:

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter54ApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CacheManager cacheManager;

    @Test
    public void test() throws Exception {
        System.out.println("CacheManager type : " + cacheManager.getClass());

        // 创建1条记录
        userRepository.save(new User("AAA", 10));

        User u1 = userRepository.findByName("AAA");
        System.out.println("第一次查询:" + u1.getAge());

        User u2 = userRepository.findByName("AAA");
        System.out.println("第二次查询:" + u2.getAge());
    }

}

Executing the test output can get:

CacheManager type : class org.springframework.data.redis.cache.RedisCacheManager
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into user (age, name, id) values (?, ?, ?)
2020-08-12 16:25:26.954  INFO 68282 --- [           main] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2020-08-12 16:25:26.955  INFO 68282 --- [           main] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
第一次查询:10
第二次查询:10

can be seen:

  1. CacheManager type as the first line of output org.springframework.data.redis.cache.RedisCacheManager, rather than one of EhCacheCacheManagerthe
  2. In the second query, no SQL statement was output, so it was obtained from the cache

Successful integration!

Questions

Since EhCache and other in-process caches have consistency problems, and Redis has good performance and can solve the consistency problems, then we only need to learn to use Redis. Why do we need to learn in-process caching? Leave your thoughts first, let's discuss this issue together in the next article! Welcome to follow this series of tutorials: "Spring Boot 2.x Basic Tutorial"

Code example

For related examples in this article, you can view the chapter5-4directories in the following warehouse :

If you think this article is good, Staryou are welcome to support it. Your attention is my motivation for persistence!

This article is first published : Spring Boot 2.x Basic Tutorial: Using Centralized Cache Redis , please indicate the source for reprinting. Welcome to pay attention to my official account: Program Ape DD, to get exclusive learning resources and daily dry goods push. Click directly to the catalog of this series of tutorials .

Guess you like

Origin blog.csdn.net/dyc87112/article/details/107989725