天天看点

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