Spring-Boot实战|分布式缓存-JPA的二级缓存-Redis

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: 以JPA为ORM框架的微服务,默认是二级缓存是关闭的。因为在分布式集群架构下,本地的二级缓存必然会带来多个微服务实例缓存不一致问题。将二级缓存移交给第三方中间件可以很好的解决缓存不一致问题。而Redis一款高性能的K-V存储中间件,在保证缓存一致性的同时,还能提供高性能,高可用的特性。本篇文章就是基于开源框架Hibernate-Redis,将Redis作为为JPA的二级缓存实现

Hibernate-Redis集成

GitHub地址

介绍

Spring Boot 中,以JPAORM框架的微服务,默认是二级缓存是关闭的。因为在分布式集群架构下,本地的二级缓存必然会带来多个微服务实例缓存不一致问题。将二级缓存移交给第三方中间件可以很好的解决缓存不一致问题。并且Redis一款高性能的K-V存储中间件,在保证缓存一致性的同时,还能提供高性能,高可用的特性。本篇文章就是基于开源框架hibernate-redisGitHub地址,将redis集成到微服务中作为JPA中作为二级缓存存储中间件。
###集成
hibernate-redisConfiguration官方给很多种集成方式,针对于不同redis模式(redis单体模式主从模式哨兵模式,集群模式)给出了不同配置说明,本文为以最简单redis单体模式,将redis集成到服务中。
0. redis安装启动
将redis安装并启动,本文redis的地址为:127.0.0.1:6379

1. 引入pom

   <dependency>
          <groupId>com.github.debop</groupId>
          <artifactId>hibernate-redis</artifactId>
          <version>2.4.0</version>
      </dependency>

      <dependency>
          <groupId>org.redisson</groupId>
          <artifactId>redisson</artifactId>
          <version>2.5.1</version>
      </dependency>
      <dependency>
          <groupId>de.ruedigermoeller</groupId>
          <artifactId>fst</artifactId>
          <version>2.48</version>
      </dependency>
      <dependency>
          <groupId>org.xerial.snappy</groupId>
          <artifactId>snappy-java</artifactId>
          <version>1.1.7.3</version>
      </dependency>

2 . 配置
A . 在 src/main/resources/application.yml 配置数据源和开启二级缓存

spring:
  application:
    name: jps-redis-demo
  datasource:
    username: root
    password: *****
    url: jdbc:mysql://localhost:3306/tenant-center?&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
  jpa:
    hibernate:
      naming:
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
      ddl-auto: update
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    properties:
      ## 缓存策略,总是缓存
      javax:
        persistence:
          sharedCache:
            mode: ALL
      ##二级缓存配置
      hibernate:
        cache:
          ## 开启二级缓存
          use_second_level_cache: true
          ## 查询缓存
          use_query_cache: true
          ## RedisRegionFactory
          region:
            factory_class: org.hibernate.cache.redis.hibernate52.SingletonRedisRegionFactory
          ## 缓存标示前缀
          region_prefix: hibernate
          ## 结构化缓存实体
          use_structured_entries: true
          ## 配置文件路径
          provider_configuration_file_resource_path: classpath:conf/hibernate-redis.properties
      redisson-config: classpath:conf/redisson.yaml
      redis:
        expiryInSeconds:
          default: 120
          hibernate:
            common: 0
            account: 1200
    show-sql: true

缓存模式 javax.persistence.shared.Cache.mode
官方解释:SharedCacheMode
文本以ALL 表示:所有实体都缓存

B . 在 src/main/resources/创建 conf目录存放hibernate-redis的配置文件,并创建hibernate-redis.propertiesredisson.yaml 配置文件
企业微信20200410045800.png

hibernate-redis.properties 配置文件:

redisson-config=classpath:conf/redisson.yaml
#
# Cache Expiry settings
# 'hibernate' is second cache prefix
# 'common', 'account' is actual region name
#
# default = 120 seconds (2 minutes) (see RedisCacheUtil.DEFAULT_EXPIRY_IN_SECONDS)
#
redis.expiryInSeconds.default=360
redis.expiryInSeconds.hibernate.common=0
redis.expiryInSeconds.hibernate.account=1200

redisson.yaml 配置文件:

singleServerConfig:
## If pooled connection not used for a timeout time and current connections amount bigger than minimum idle connections pool size, then it will closed and removed from pool. Value in milliseconds.
  idleConnectionTimeout: 10000
## Timeout during connecting to any Redis server.
  connectTimeout: 10000
## Redis server response timeout. Starts to countdown when Redis command was succesfully sent. Value in milliseconds.
  timeout: 3000
## Error will be thrown if Redis command can't be sended to Redis server after retryAttempts. But if it sent succesfully then timeout will be started.
  retryAttempts: 3
## Time interval after which another one attempt to send Redis command will be executed. Value in milliseconds
  retryInterval: 1500
## Password for Redis server authentication
  password: null
## Subscriptions per subscribe connection limit. Used by RTopic, RPatternTopic, RLock, RSemaphore, RCountDownLatch, RClusteredLocalCachedMap, RClusteredLocalCachedMapCache, RLocalCachedMap, RLocalCachedMapCache objects and Hibernate READ_WRITE cache strategy.
  subscriptionsPerConnection: 5
## Name of client connection
  clientName: null
## Redis server address in host:port format. Use rediss:// protocol for SSL connection.
  address:
  - "redis://127.0.0.1:6379"
## Minimum idle Redis subscription connection amount.
  subscriptionConnectionMinimumIdleSize: 1
## Redis subscription connection maximum pool size.
  subscriptionConnectionPoolSize: 50
## Minimum idle Redis connection amount.
  connectionMinimumIdleSize: 24
## Redis connection maximum pool size.
  connectionPoolSize: 64
## Database index used for Redis connection
  database: 0
## DNS change monitoring interval. Applications must ensure the JVM DNS cache TTL is low enough to support this. Set -1 to disable. Multiple IP bindings for single hostname supported in Proxy mode.
  dnsMonitoringInterval: 5000
threads: 16
## Threads amount shared between all redis clients used by Redisson. Netty threads used in Redis response decoding and command sending.
nettyThreads: 32
## Redis data codec. Used during read and write Redis data. Several implementations are available:
codec: !<org.redisson.codec.FstCodec> {}
## Available values: default  TransportMode.NIO
#TransportMode.NIO,
#TransportMode.EPOLL - requires netty-transport-native-epoll lib in classpath
#TransportMode.KQUEUE - requires netty-transport-native-kqueue lib in classpath
## transportMode: "NIO"

配置文件中都有关于配置的官方说明,其中transportMode:"NIO" 为默认配置,可以不配置,配置会导致文件格式解析问题。

3 . 注解启动
在启动类上加入缓存启动注解

@SpringBootApplication
@EnableCaching
public class JpaRedisDemoApplication {

  public static void main(String[] args) { SpringApplication.run(JpaRedisDemoApplication.class, args);}

}

3 . 创建实体测试

  创建相应的实体测试二级缓存是否生效。

就这样简单四个步骤就可以将hibernate-redis集成到JPA

版本说明

hibernate-redis 官方发布的版本为2.3.2 ,可以支持hibernate (4.x, 5.1.x, 5.2.x) ,但是本文在集成该hibernate-core-5.2.11.Final版本,
出现问题:

官方的问题列表中也存在这个问题,并且说明在hibernate-redis-2.4.0 版本中解决,但2.4.0 版本还未发布,需要手动下载jar,并安装到本地仓库中去
下载地址:hibernate-redis-2.4.0
安装命令:

mvn install:install-file -Dfile=hibernate-redis-2.4.0.jar -DgroupId=com.github.debop -DartifactId=hibernate-redis -Dversion=2.4.0 -Dpackaging=jar

源代码实例

本篇源代码实例:jpa-redis-demo

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
19天前
|
存储 缓存 NoSQL
分布式系统架构8:分布式缓存
本文介绍了分布式缓存的理论知识及Redis集群的应用,探讨了AP与CP的区别,Redis作为AP系统具备高性能和高可用性但不保证强一致性。文章还讲解了透明多级缓存(TMC)的概念及其优缺点,并详细分析了memcached和Redis的分布式实现方案。此外,针对缓存穿透、击穿、雪崩和污染等常见问题提供了应对策略,强调了Cache Aside模式在解决数据一致性方面的作用。最后指出,面试中关于缓存的问题多围绕Redis展开,建议深入学习相关知识点。
120 8
|
3月前
|
NoSQL 安全 测试技术
Redis游戏积分排行榜项目中通义灵码的应用实战
Redis游戏积分排行榜项目中通义灵码的应用实战
97 4
|
22天前
|
存储 缓存 安全
分布式系统架构7:本地缓存
这是小卷关于分布式系统架构学习的第10篇文章,主要介绍本地缓存的基础理论。文章分析了引入缓存的利弊,解释了缓存对CPU和I/O压力的缓解作用,并讨论了缓存的吞吐量、命中率、淘汰策略等属性。同时,对比了几种常见的本地缓存工具(如ConcurrentHashMap、Ehcache、Guava Cache和Caffeine),详细介绍了它们的访问控制、淘汰策略及扩展功能。
47 6
|
3月前
|
存储 Java 关系型数据库
在Spring Boot中整合Seata框架实现分布式事务
可以在 Spring Boot 中成功整合 Seata 框架,实现分布式事务的管理和处理。在实际应用中,还需要根据具体的业务需求和技术架构进行进一步的优化和调整。同时,要注意处理各种可能出现的问题,以保障分布式事务的顺利执行。
203 53
|
2月前
|
存储 NoSQL Java
使用lock4j-redis-template-spring-boot-starter实现redis分布式锁
通过使用 `lock4j-redis-template-spring-boot-starter`,我们可以轻松实现 Redis 分布式锁,从而解决分布式系统中多个实例并发访问共享资源的问题。合理配置和使用分布式锁,可以有效提高系统的稳定性和数据的一致性。希望本文对你在实际项目中使用 Redis 分布式锁有所帮助。
192 5
|
2月前
|
缓存 NoSQL Java
Spring Boot中的分布式缓存方案
Spring Boot提供了简便的方式来集成和使用分布式缓存。通过Redis和Memcached等缓存方案,可以显著提升应用的性能和扩展性。合理配置和优化缓存策略,可以有效避免常见的缓存问题,保证系统的稳定性和高效运行。
71 3
|
4月前
|
NoSQL 关系型数据库 MySQL
MySQL与Redis协同作战:优化百万数据查询的实战经验
【10月更文挑战第13天】 在处理大规模数据集时,传统的关系型数据库如MySQL可能会遇到性能瓶颈。为了提升数据处理的效率,我们可以结合使用MySQL和Redis,利用两者的优势来优化数据查询。本文将分享一次实战经验,探讨如何通过MySQL与Redis的协同工作来优化百万级数据统计。
178 5
|
4月前
|
自然语言处理 Java API
Spring Boot 接入大模型实战:通义千问赋能智能应用快速构建
【10月更文挑战第23天】在人工智能(AI)技术飞速发展的今天,大模型如通义千问(阿里云推出的生成式对话引擎)等已成为推动智能应用创新的重要力量。然而,对于许多开发者而言,如何高效、便捷地接入这些大模型并构建出功能丰富的智能应用仍是一个挑战。
590 6
|
4月前
|
缓存 NoSQL Java
Spring Boot与Redis:整合与实战
【10月更文挑战第15天】本文介绍了如何在Spring Boot项目中整合Redis,通过一个电商商品推荐系统的案例,详细展示了从添加依赖、配置连接信息到创建配置类的具体步骤。实战部分演示了如何利用Redis缓存提高系统响应速度,减少数据库访问压力,从而提升用户体验。
225 2
|
2月前
|
存储 缓存 NoSQL
解决Redis缓存数据类型丢失问题
解决Redis缓存数据类型丢失问题
184 85