開發與維運

Spring-Boot實戰|分佈式緩存-JPA的二級緩存-Redis

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

Leave a Reply

Your email address will not be published. Required fields are marked *