本篇内容介绍了“Spring Boot中怎么使用集中式缓存Redis”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
动手试试
User实体的定义
@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实体的数据访问实现(涵盖了缓存注解)
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {
@Cacheable
User findByName(String name);
}
(推荐课程:Spring教程)
下面开始改造这个项目:
第一步:pom.xml
中增加相关依赖:
<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>
在Spring Boot 1.x
的早期版本中,该依赖的名称为spring-boot-starter-redis
,所以在Spring Boot 1.x
基础教程中与这里不同。
第二步:配置文件中增加配置信息,以本地运行为例,比如:
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
关于连接池的配置,需要注意:
Redis
的连接池配置在 1.x 版本中前缀为spring.redis.pool
与Spring Boot 2.x
有所不同。在 1.x 版本中采用jedis
作为连接池,而在 2.x 版本中采用了lettuce
作为连接池以上配置均为默认值,实际上生产需进一步根据部署情况与业务要求做适当修改.
再来试试单元测试:
@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());
}
}
执行测试输出可以得到:
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 nextval=?
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 id10, user0_.age as age20, user0_.name as name30 from user user0 where user0.name=?
第一次查询:10
第二次查询:10
(推荐微课:Spring微课)
可以看到:
第一行输出的CacheManager type
为org.springframework.data.redis.cache.RedisCacheManager
,而不是上一篇中的EhCacheCacheManager
了
第二次查询的时候,没有输出SQL语句,所以是走的缓存获取
“Spring Boot中怎么使用集中式缓存Redis”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注天达云网站,小编将为大家输出更多高质量的实用文章!