Data Grid Spring Boot Starter


Red Hat Data Grid 8.2

将 Data Grid 与 Spring Boot 项目搭配使用

Red Hat Customer Content Services

摘要

快速使 Spring Boot 项目使用一组受管传输依赖项启动并运行,其中包括您的 Spring Boot 项目需要与 Data Grid 无缝交互。请注意,虽然 Data Grid Spring Boot starter 为您提供了开始使用 Spring Boot 的便捷方法,但它是可选的。要将 Data Grid 与 Spring Boot 搭配使用,您只需添加您想要的依赖项。

Red Hat Data Grid

Data Grid 是一个高性能分布式内存数据存储。

无架构数据结构
将不同对象存储为键值对的灵活性。
基于网格的数据存储
旨在在集群中分发和复制数据。
弹性扩展
动态调整节点数量,以便在不中断服务的情况下满足需求。
数据互操作性
从不同端点在网格中存储、检索和查询数据。

Data Grid 文档

红帽客户门户网站中提供了 Data Grid 的文档。

Data Grid 下载

访问红帽客户门户上的 Data Grid 软件下载

注意

您必须有一个红帽帐户才能访问和下载数据中心软件。

使开源包含更多

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。我们从这四个术语开始:master、slave、黑名单和白名单。由于此项工作十分艰巨,这些更改将在即将推出的几个发行版本中逐步实施。有关更多详情,请参阅我们的首席技术官 Chris Wright 提供的消息

第 1 章 设置项目

在您的项目中添加 Data Grid Spring Boot Starter 的依赖项。

1.1. 强制数据网格版本

此入门程序使用高级别 API 来确保 Data Grid 的主要版本间的兼容性。但是,您可以使用 infinispan-bom 模块强制使用特定版本的 Data Grid。

流程

  • 在启动程序依赖项前,将 infinispan-bom 添加到 pom.xml 文件中。

    <properties>
      <version.infinispan>12.1.11.Final-redhat-00001</version.infinispan>
    </properties>
    
    <dependencyManagement>
        <dependencies>
           <dependency>
               <groupId>org.infinispan</groupId>
               <artifactId>infinispan-bom</artifactId>
               <version>${version.infinispan}</version>
               <type>pom</type>
               <scope>import</scope>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-parent</artifactId>
               <version>${version.spring.boot}</version>
               <type>pom</type>
               <scope>import</scope>
           </dependency>
           <dependency>
               <groupId>org.infinispan</groupId>
               <artifactId>infinispan-spring-boot-starter</artifactId>
           </dependency>
        </dependencies>
     </dependencyManagement>
    Copy to Clipboard Toggle word wrap
重要

Data Grid Spring Boot starter 对其他项目(如 Red Hat OpenShift Application Runtimes)使用不同的 Spring Boot 版本。如果要使用特定的 Spring Boot 版本与其他项目兼容,您必须在项目中添加正确的依赖项。

1.2. 为使用模式添加依赖项

Data Grid 为嵌入式缓存和远程缓存提供不同的依赖项。

流程

  • pom.xml 文件中添加以下内容之一:

嵌入式缓存

<dependency>
  <groupId>org.infinispan</groupId>
  <artifactId>infinispan-spring-boot-starter-embedded</artifactId>
</dependency>
Copy to Clipboard Toggle word wrap

远程缓存

<dependency>
  <groupId>org.infinispan</groupId>
  <artifactId>infinispan-spring-boot-starter-remote</artifactId>
</dependency>
Copy to Clipboard Toggle word wrap

第 2 章 使用嵌入式缓存

在项目中直接嵌入 Data Grid 缓存,以进行内存数据存储。

2.1. 添加 EmbeddedCacheManager Bean

配置您的应用程序以使用嵌入式缓存。

流程

  1. infinispan-spring-boot-starter-embedded 添加到项目的 classpath 中,以启用 Embedded 模式。
  2. 使用 Spring @Autowired 注解在 Java 配置类中包含 EmbededCacheManager bean,如下例所示:

    private final EmbeddedCacheManager cacheManager;
    
    @Autowired
    public YourClassName(EmbeddedCacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }
    Copy to Clipboard Toggle word wrap

现在,您可以在应用程序中直接使用 Data Grid 缓存,如下例所示:

cacheManager.getCache("testCache").put("testKey", "testValue");
System.out.println("Received value from cache: " + cacheManager.getCache("testCache").get("testKey"));
Copy to Clipboard Toggle word wrap

2.2. 缓存管理器配置 Beans

您可以使用以下配置 Bean 自定义缓存管理器:

  • InfinispanGlobalConfigurer
  • InfinispanCacheConfigurer
  • 配置
  • InfinispanConfigurationCustomizer
  • InfinispanGlobalConfigurationCustomizer
注意

您只能创建一个 InfinispanGlobalConfigurer bean。但是,您可以使用其他 Bean 创建多个配置。

InfinispanCacheConfigurer Bean

@Bean
public InfinispanCacheConfigurer cacheConfigurer() {
	return manager -> {
		final Configuration ispnConfig = new ConfigurationBuilder()
                        .clustering()
                        .cacheMode(CacheMode.LOCAL)
                        .build();

		manager.defineConfiguration("local-sync-config", ispnConfig);
	};
}
Copy to Clipboard Toggle word wrap

配置 Bean

将 bean 名称链接到它配置的缓存,如下所示:

@Bean(name = "small-cache")
public org.infinispan.configuration.cache.Configuration smallCache() {
    return new ConfigurationBuilder()
        .read(baseCache)
        .memory().size(1000L)
        .memory().evictionType(EvictionType.COUNT)
        .build();
}

@Bean(name = "large-cache")
public org.infinispan.configuration.cache.Configuration largeCache() {
    return new ConfigurationBuilder()
        .read(baseCache)
        .memory().size(2000L)
        .build();
}
Copy to Clipboard Toggle word wrap

Customizer Beans

@Bean
public InfinispanGlobalConfigurationCustomizer globalCustomizer() {
   return builder -> builder.transport().clusterName(CLUSTER_NAME);
}

@Bean
public InfinispanConfigurationCustomizer configurationCustomizer() {
   return builder -> builder.memory().evictionType(EvictionType.COUNT);
}
Copy to Clipboard Toggle word wrap

2.3. 启用 Spring 缓存支持

通过嵌入式和远程缓存,Data Grid 提供了可以启用的 Spring Cache 的实现。

流程

  • @EnableCaching 注释添加到您的应用程序。

如果 Data Grid starter 检测到:

  • EmbeddedCacheManager bean,它会实例化一个新的 SpringEmbeddedCacheManager
  • RemoteCacheManager bean,它实例化一个新的 SpringRemoteCacheManager

第 3 章 使用远程缓存

使用 Hot Rod (一个自定义 TCP 二进制线协议)从远程 Data Grid 集群存储和检索数据。

3.1. 设置 RemoteCacheManager

将应用程序配置为在 Data Grid 集群上使用远程缓存。

  1. 提供 Data Grid 服务器侦听客户端连接的地址,以便启动程序可以创建 RemoteCacheManager bean。
  2. 使用 Spring @Autowired 注解在应用程序中包含您自己的自定义缓存管理器类:

    private final RemoteCacheManager cacheManager;
    
    @Autowired
    public YourClassName(RemoteCacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }
    Copy to Clipboard Toggle word wrap

3.1.1. 属性文件

您可以在 hotrod-client.propertiesapplication.properties 中指定属性。

属性可以在这两个属性文件中,但启动程序首先应用 hotrod-client.properties 中的配置,这意味着文件优先于 application.properties

hotrod-client.properties

此文件中的属性的格式采用 infinispan.client.hotrodö 的格式,例如:

# List Data Grid servers by IP address or hostname at port 11222.
infinispan.client.hotrod.server_list=127.0.0.1:6667
Copy to Clipboard Toggle word wrap
application.properties

此文件中的属性的格式采用 infinispan.remote.* 格式,例如:

# List Data Grid servers by IP address or hostname at port 11222.
infinispan.remote.server-list=127.0.0.1:6667
Copy to Clipboard Toggle word wrap

3.2. 配置 Marshalling

配置 Data Grid 对 Java 对象进行 marshall 处理生成二进制格式,以便它们可以进行有线传输或存储到磁盘。

默认情况下,Data Grid 使用 Java Serialization marshaller,这需要将您的类添加到允许列表中。作为替代方案,您可以使用 ProtoStream,这需要注解类并为自定义 Java 对象生成 SerializationContextInitializer

流程

  1. 打开 hotrod-client.propertiesapplication.properties 进行编辑。
  2. 执行以下操作之一:

    • 使用 ProtoStream 作为 marshaller。

      infinispan.client.hotrod.marshaller=org.infinispan.commons.marshall.ProtoStreamMarshaller
      Copy to Clipboard Toggle word wrap
      infinispan.remote.marshaller=org.infinispan.commons.marshall.ProtoStreamMarshaller
      Copy to Clipboard Toggle word wrap
    • 如果使用 Java 序列化,请将类添加到序列化允许列表中。您可以指定以逗号分隔的完全限定类名称或正则表达式列表来匹配类。

      infinispan.client.hotrod.java_serial_allowlist=your_marshalled_beans_package.*
      Copy to Clipboard Toggle word wrap
      infinispan.remote.java-serial-allowlist=your_marshalled_beans_package.*
      Copy to Clipboard Toggle word wrap
  3. 保存并关闭您的属性文件。

3.3. 缓存管理器配置 Beans

使用以下配置 Bean 自定义缓存管理器:

  • InfinispanRemoteConfigurer
  • 配置
  • InfinispanRemoteCacheCustomizer
注意

您只能创建一个 InfinispanRemoteConfigurer bean。但是,您可以使用其他 Bean 创建多个配置。

InfinispanRemoteConfigurer Bean

@Bean
public InfinispanRemoteConfigurer infinispanRemoteConfigurer() {
    return () -> new ConfigurationBuilder()
        .addServer()
        .host("127.0.0.1")
        .port(12345)
        .build();
}
Copy to Clipboard Toggle word wrap

配置 Bean

@Bean
public org.infinispan.client.hotrod.configuration.Configuration customConfiguration() {
    new ConfigurationBuilder()
        .addServer()
        .host("127.0.0.1")
        .port(12345)
        .build();
}
Copy to Clipboard Toggle word wrap

InfinispanRemoteCacheCustomizer Bean

@Bean
public InfinispanRemoteCacheCustomizer customizer() {
    return b -> b.tcpKeepAlive(false);
}
Copy to Clipboard Toggle word wrap

提示

使用 @Ordered 注释以特定顺序应用自定义器。

3.4. 启用 Spring 缓存支持

通过嵌入式和远程缓存,Data Grid 提供了可以启用的 Spring Cache 的实现。

流程

  • @EnableCaching 注释添加到您的应用程序。

如果 Data Grid starter 检测到:

  • EmbeddedCacheManager bean,它会实例化一个新的 SpringEmbeddedCacheManager
  • RemoteCacheManager bean,它实例化一个新的 SpringRemoteCacheManager

3.5. 公开数据网格统计

Data Grid 支持 Spring Boot Actuator 将缓存统计信息作为指标公开。

流程

  1. 在您的 pom.xml 文件中添加以下内容:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
      <version>${version.spring.boot}</version>
     </dependency>
    
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>${version.spring.boot}</version>
    </dependency>
    Copy to Clipboard Toggle word wrap
  2. 以编程方式或声明性方式激活相应缓存实例的统计信息。

    以编程方式

    @Bean
    public InfinispanCacheConfigurer cacheConfigurer() {
      return cacheManager -> {
         final org.infinispan.configuration.cache.Configuration config =
               new ConfigurationBuilder()
                     .jmxStatistics().enable()
                     .build();
    
         cacheManager.defineConfiguration("my-cache", config);
      };
    }
    Copy to Clipboard Toggle word wrap

    声明性

    <local-cache name="mycache" statistics="true"/>
    Copy to Clipboard Toggle word wrap

Spring Boot Actuator registry 在应用程序启动时绑定缓存实例。

如果您动态创建缓存,您应该使用 CacheMetricsRegistrar bean 将缓存绑定到 Actuator registry,如下所示:

@Autowire
CacheMetricsRegistrar cacheMetricsRegistrar;

@Autowire
CacheManager cacheManager;
...

cacheMetricsRegistrar.bindCacheToRegistry(cacheManager.getCache("my-cache"));
Copy to Clipboard Toggle word wrap

第 4 章 使用 Spring 会话

4.1. 启用 Spring 会话支持

Data Grid Spring Session 支持基于 SpringRemoteCacheManagerSpringEmbeddedCacheManager 构建。Data Grid starter 默认生成这些 Bean。

流程

  1. 将此启动程序添加到您的项目中。
  2. 将 Spring Session 添加到类路径。
  3. 在您的配置中添加以下注解:

    • @EnableCaching
    • @EnableInfinispanRemoteHttpSession
    • @EnableInfinispanEmbeddedHttpSession
注意

Data Grid 不提供默认缓存。要使用 Spring Session,您必须首先创建一个 Data Grid 缓存。

第 5 章 应用程序属性

使用 application.propertiesapplication.yaml 配置您的项目。

#
# Embedded Properties - Uncomment properties to use them.
#

# Enables embedded capabilities in your application.
# Values are true (default) or false.
#infinispan.embedded.enabled =

# Sets the Spring state machine ID.
#infinispan.embedded.machineId =

# Sets the name of the embedded cluster.
#infinispan.embedded.clusterName =

# Specifies a XML configuration file that takes priority over the global
# configuration bean or any configuration customizer.
#infinispan.embedded.configXml =

#
# Server Properties - Uncomment properties to use them.
#

# Specifies a custom filename for Hot Rod client properties.
#infinispan.remote.clientProperties =

# Enables remote server connections.
# Values are true (default) or false.
#infinispan.remote.enabled =

# Defines a comma-separated list of servers in this format:
# `host1[:port],host2[:port]`.
#infinispan.remote.server-list=

# Sets a timeout value, in milliseconds, for socket connections.
#infinispan.remote.socketTimeout =

# Sets a timeout value for initializing connections with servers.
#infinispan.remote.connectTimeout =

# Sets the maximum number of attempts to connect to servers.
#infinispan.remote.maxRetries =

# Specifies the marshaller to use.
#infinispan.remote.marshaller =

# Adds your classes to the serialization allow list.
#infinispan.remote.java-serial-allowlist=
Copy to Clipboard Toggle word wrap

法律通告

Copyright © 2023 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, the Red Hat logo, JBoss, OpenShift, Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.
Linux® is the registered trademark of Linus Torvalds in the United States and other countries.
Java® is a registered trademark of Oracle and/or its affiliates.
XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries.
MySQL® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Node.js® is an official trademark of Joyent. Red Hat is not formally related to or endorsed by the official Joyent Node.js open source or commercial project.
The OpenStack® Word Mark and OpenStack logo are either registered trademarks/service marks or trademarks/service marks of the OpenStack Foundation, in the United States and other countries and are used with the OpenStack Foundation's permission. We are not affiliated with, endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.
All other trademarks are the property of their respective owners.
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat