@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;
}
}@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的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号