Previously, we introduced two uses of in-process caching , Include Spring Boot Default ConcurrentMap cache as well as Caching framework EhCache. although EhCache Has been able to apply to many application scenarios , But because of EhCache It’s an in-process caching framework , In cluster mode , The caching between application servers is independent , Therefore, there will be cache inconsistencies between processes on different servers . Even if EhCache Provides cache synchronization strategy in cluster environment , But synchronization still takes time , Transient cache inconsistencies still exist .
In some cases, high consistency is required ( Any data change can be queried in time ) In the system and application of , It can’t be used anymore EhCache To solve the , At this time, the use of centralized cache can solve the problem of cache data consistency . Next, let’s learn about , How to be in Spring Boot In cache support Redis Implement data caching .
Try it
The implementation of this article will be based on Last one To carry out the basic engineering of . Let’s review the procedural elements from the previous article :
User Definition of 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 ( Includes cache annotations )
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {
@Cacheable
User findByName(String name);
}
Now let’s start transforming this project :
First step :pom.xml
Add related dependence in :
<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>
stay Spring Boot 1.x In an earlier version , The name of the dependency is
spring-boot-starter-redis
, So in Spring Boot 1.x Basic course It’s different from here .
The second step : 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
About connection pool configuration , Pay attention to some points. :
- Redis The connection pool is configured in 1.x The prefix in the version is
spring.redis.pool
And Spring Boot 2.x Somewhat different .- stay 1.x The version uses jedis As a connection pool , And in the 2.x The lettuce As a connection pool
- The above configuration is the default value , In fact, production needs to be further modified according to the deployment and business requirements .
Try unit testing 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());
// establish 1 Bar record
userRepository.save(new User("AAA", 10));
User u1 = userRepository.findByName("AAA");
System.out.println(" First query :" + u1.getAge());
User u2 = userRepository.findByName("AAA");
System.out.println(" Second query :" + u2.getAge());
}
}
Execute the test output to 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=?
First query :10
Second query :10
You can see :
- The first line outputs CacheManager type by
org.springframework.data.redis.cache.RedisCacheManager
, Not the one in the last oneEhCacheCacheManager
了 - On the second inquiry , No output SQL sentence , So it’s going to take cache access
Successful integration !
Thinking questions
since EhCache In process cache consistency problems exist , and Redis Good performance and can solve the problem of consistency , So we just need to learn to use Redis That’s it , Why learn in-process caching ? Leave your thoughts behind , Let’s talk about this next time ! Welcome to this series of tutorials :《Spring Boot 2.x Basic course 》
Code example
For an example of this article, see the following in the warehouse chapter5-4
Catalog :
- Github:https://github.com/dyc87112/SpringBoot-Learning/
- Gitee:https://gitee.com/didispace/SpringBoot-Learning/
If you think this article is good , welcome Star
Support , Your concern is the driving force of my persistence !
First article :Spring Boot 2.x Basic course : Using centralized caching Redis, Reprint please indicate the source . Welcome to my official account. : Program the ape DD, Get exclusive learning resources and daily dry goods push . Click to the contents of this series .