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

简介: 以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

目录
相关文章
|
缓存 NoSQL 关系型数据库
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
|
缓存 NoSQL Java
Redis+Caffeine构建高性能二级缓存
大家好,我是摘星。今天为大家带来的是Redis+Caffeine构建高性能二级缓存,废话不多说直接开始~
1768 0
|
10月前
|
缓存 负载均衡 监控
135_负载均衡:Redis缓存 - 提高缓存命中率的配置与最佳实践
在现代大型语言模型(LLM)部署架构中,缓存系统扮演着至关重要的角色。随着LLM应用规模的不断扩大和用户需求的持续增长,如何构建高效、可靠的缓存架构成为系统性能优化的核心挑战。Redis作为业界领先的内存数据库,因其高性能、丰富的数据结构和灵活的配置选项,已成为LLM部署中首选的缓存解决方案。
911 25
|
11月前
|
存储 缓存 NoSQL
Redis专题-实战篇二-商户查询缓存
本文介绍了缓存的基本概念、应用场景及实现方式,涵盖Redis缓存设计、缓存更新策略、缓存穿透问题及其解决方案。重点讲解了缓存空对象与布隆过滤器的使用,并通过代码示例演示了商铺查询的缓存优化实践。
408 1
Redis专题-实战篇二-商户查询缓存
|
11月前
|
NoSQL Java 调度
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
分布式锁是分布式系统中用于同步多节点访问共享资源的机制,防止并发操作带来的冲突。本文介绍了基于Spring Boot和Redis实现分布式锁的技术方案,涵盖锁的获取与释放、Redis配置、服务调度及多实例运行等内容,通过Docker Compose搭建环境,验证了锁的有效性与互斥特性。
888 0
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
|
10月前
|
缓存 运维 监控
Redis 7.0 高性能缓存架构设计与优化
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Redis 7.0高性能缓存架构,探索函数化编程、多层缓存、集群优化与分片消息系统,用代码在二进制星河中谱写极客诗篇。
1826 3
|
11月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
1836 5
|
11月前
|
缓存 NoSQL 关系型数据库
Redis缓存和分布式锁
Redis 是一种高性能的键值存储系统,广泛用于缓存、消息队列和内存数据库。其典型应用包括缓解关系型数据库压力,通过缓存热点数据提高查询效率,支持高并发访问。此外,Redis 还可用于实现分布式锁,解决分布式系统中的资源竞争问题。文章还探讨了缓存的更新策略、缓存穿透与雪崩的解决方案,以及 Redlock 算法等关键技术。
|
11月前
|
存储 缓存 Java
Spring中@Cacheable、@CacheEvict以及其他缓存相关注解的实用介绍
缓存是提升应用性能的重要技术,Spring框架提供了丰富的缓存注解,如`@Cacheable`、`@CacheEvict`等,帮助开发者简化缓存管理。本文介绍了如何在Spring中配置缓存管理器,使用缓存注解优化数据访问,并探讨了缓存的最佳实践,以提升系统响应速度与可扩展性。
458 0
Spring中@Cacheable、@CacheEvict以及其他缓存相关注解的实用介绍
|
NoSQL Java Redis
Redis基本数据类型及Spring Data Redis应用
Redis 是开源高性能键值对数据库,支持 String、Hash、List、Set、Sorted Set 等数据结构,适用于缓存、消息队列、排行榜等场景。具备高性能、原子操作及丰富功能,是分布式系统核心组件。
855 2