我们介绍了两种进程内缓存的用法,包括SpringBoot默认使用的ConcurrentMap缓存和缓存框架EhCache。虽然EhCache已经可以应用于很多应用场景,但是由于EhCache是??一个进程内缓存框架,在集群模式下,应用服务器之间的缓存是独立的,所以不同服务器的进程之间会存在缓存不一致的情况。即使EhCache在集群环境下提供了缓存同步策略,但是同步还是需要一定的时间,临时缓存不一致的情况依然存在。在一些要求高一致性的系统和应用中(任何数据变化都可以及时查询),EhCache已经不能用来解决问题了。这时候集中缓存可以很好的解决缓存数据的一致性问题。问题。下面我们就来学习一下在SpringBoot的缓存支持中,如何使用Redis来实现数据缓存。亲自尝试本文的实现将基于上一篇文章的基础项目。先回顾一下上篇的程序元素:用户实体定义@Entity@Data@NoArgsConstructorpublicclassUserimplementsSerializable{@Id@GeneratedValueprivateLongid;privateStringname;privateIntegerage;publicUser(Stringname,Integerage){this.name=name;this.age=age;}}用户实体的数据访问实现(涵盖缓存注解)@CacheConfig(cacheNames="users")publicinterfaceUserRepositoryextendsJpaRepository{@CacheableUserfindByName(Stringname);}让我们开始改造这个项目:第一步:pom.在xml中添加相关依赖:org.springframework.bootspring-boot-starter-data-redisorg.apache.commonscommons-pool2在早期的SpringBoot1.x版本中,依赖的名字是spring-boot-starter-redis,所以在SpringBoot1.和这里的x基础教程不同。第二步:在配置文件中添加配置信息,以本地运行为例,例如:spring.redis.host=localhostspring.redis.port=6379spring.redis.lettuce.pool.max-idle=8spring.redis.lettuce.pool.max-active=8spring.redis.lettuce.pool.max-wait=-1msspring.redis.lettuce.pool.min-idle=0spring.redis.lettuce.shutdown-timeout=100ms关于连接池的配置,需要注意几点:Redis的连接池配置在1.x版本中以spring.redis.pool为前缀,而SpringBoot2.x有所不同。1.x版本使用jedis作为连接池,2.x版本使用lettuce作为连接池。以上配置均为默认值。实际上生产还需要根据部署情况和业务需求做进一步修改。再试一次单元测试:@Slf4j@RunWith(SpringRunner.class)@SpringBootTestpublicclassChapter54ApplicationTests{@AutowiredprivateUserRepositoryuserRepository;@AutowiredprivateCacheManagercacheManager;@Testpublicvoidtest()throwsException{System.out.println("CacheManagertype:"+cacheManager);/getClass()记录userRepository。save(newUser("AAA",10));Useru1=userRepository.findByName("AAA");System.out.println("第一次查询:"+u1.getAge());Useru2=userRepository.findByName("AAA");System.out.println("第二次查询:"+u2.getAge());}}执行测试输出得到:CacheManagertype:classorg.springframework.data.redis.cache.RedisCacheManagerHibernate:selectnext_valasid_valfromhibernate_sequenceforupdateHibernate:updatehibernate_sequencesetnext_val=?wherenext_val=?Hibernate:insertintouser(age,name,id)values(?,?,?)2020-08-1216:25:26.954INPO68282---[main]io.Protucel.Ecore。vider:Startingwithoutoptionalalekqueuelibrary2020-08-1216:25:26.955INFO68282---[main]io.lettuce.core.KqueueProvider:StartingwithoutoptionalalkqueuelibraryHibernate:selectuser0_.idasid1_0_,user0_.ageasage2_0_,user0_.nameasname3_0_from?第一次查询:1wname_10你第二次查询:1wname_first可以看到第一行输出的CacheManager类型是org.springframework.data.redis.cache.RedisCacheManager,不是上一篇文章中的EhCacheCacheManager。第二次查询时,没有SQL语句输出。至此缓存获取整合成功!思考题既然EhCache等进程内缓存存在一致性问题,而Redis性能好,也能解决一致性问题,那么我们只需要学会使用Redis即可,为什么要学习呢?进程内缓存呢?先留下您的想法,我们将在下一篇文章中一起讨论这个问题!欢迎收看本系列教程:《Spring Boot 2.x基础教程》代码示例本文相关示例,您可以查看下面仓库中的chapter5-4目录:Github:https://github.com/dyc87112/SpringBoot-Learning/Gitee:https://gitee.com/didispace/SpringBoot-Learning/【本文为专栏作者“翟永超”原创稿件,转载请联系作者获得授权】点此阅读更多本作者好文