天天看點

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

Hibernate-Redis內建

GitHub位址

介紹

Spring Boot

中,以

JPA

ORM

架構的微服務,預設是二級緩存是關閉的。因為在分布式叢集架構下,本地的二級緩存必然會帶來多個微服務執行個體緩存不一緻問題。将二級緩存移交給第三方中間件可以很好的解決緩存不一緻問題。并且

Redis

一款高性能的

K-V

存儲中間件,在保證緩存一緻性的同時,還能提供高性能,高可用的特性。本篇文章就是基于開源架構

hibernate-redis

,将

redis

內建到微服務中作為

JPA

中作為二級緩存存儲中間件。

###內建

hibernate-redis

Configuration

官方給很多種內建方式,針對于不同

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.properties

redisson.yaml

配置檔案

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

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