Data Grid Spring Boot Starter


Red Hat Data Grid 8.1

将 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 文件中,如下所示:

<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>
           <version>2.3.6.Final-redhat-00001</version>
       </dependency>
    </dependencies>
 </dependencyManagement>
重要

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>
  <version>2.3.6.Final-redhat-00001</version>
</dependency>

远程客户端/服务器模式

<dependency>
  <groupId>org.infinispan</groupId>
  <artifactId>infinispan-spring-boot-starter-remote</artifactId>
  <version>2.3.6.Final-redhat-00001</version>
</dependency>

第 2 章 以嵌入式模式运行

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

2.1. 添加 EmbeddedCacheManager Bean

  1. infinispan-spring-boot-starter-embedded 添加到项目的 classpath 中,以启用 Embedded 模式。

    默认情况下,这个入门程序在 Remote Client/Server 模式下运行,在 classpath 上带有 infinispan-spring-boot-starter-remote

  2. 使用 Spring @Autowired 注解在 Java 配置类中包含 EmbededCacheManager bean,如下例所示:

    private final EmbeddedCacheManager cacheManager;
    
    @Autowired
    public YourClassName(EmbeddedCacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    现在,您可以以嵌入式模式使用 Data Grid。以下是一个简单的示例:

    cacheManager.getCache("testCache").put("testKey", "testValue");
    System.out.println("Received value from cache: " + cacheManager.getCache("testCache").get("testKey"));

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);
	};
}

配置 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();
}

Customizer Beans

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

@Bean
public InfinispanConfigurationCustomizer configurationCustomizer() {
   return builder -> builder.memory().evictionType(EvictionType.COUNT);
}

2.3. 启用 Spring 缓存支持

@EnableCaching 注释添加到应用以启用 Spring Cache 支持。

当此初学者检测到 EmbeddedCacheManager bean 时,它将实例化一个新的 SpringEmbeddedCacheManager,它提供 Spring Cache 的实现。

第 3 章 在服务器模式下运行

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

3.1. 设置 RemoteCacheManager

  1. 提供 Data Grid 服务器的位置,以便初学者可以创建 RemoteCacheManager bean。

    初学者首先会尝试在 hotrod-client.properties 中找到服务器位置,然后从 application.properties 中查找服务器位置。

  2. 使用 Spring @Autowired 注解在应用程序中包含您自己的自定义缓存管理器类:

    private final RemoteCacheManager cacheManager;
    
    @Autowired
    public YourClassName(RemoteCacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

热 Rod 客户端属性

在 classpath 上的 hotrod-client.properties 中指定客户端配置,例如:

# List Infinispan or Data Grid servers by IP address or hostname at port 11222.
infinispan.client.hotrod.server_list=127.0.0.1:6667

如需更多信息,请参阅 org.infinispan.client.hotrod.configuration

应用程序属性

使用 application.properties 配置项目。如需更多信息,请参阅 应用程序属性

3.2. 配置 Marshalling

配置 Data Grid 服务器,以使用 Java 序列化来 marshall 对象。

默认情况下,Data Grid 服务器使用 ProtoStream serialization 库作为默认的 marshaller。但是,Spring 集成不支持 ProtoStream marshaller。因此,您应该使用 Java Serialization Marshaller。

  • application.properties 中指定以下属性:

    infinispan.remote.marshaller=org.infinispan.commons.marshall.JavaSerializationMarshaller 
    1
    
    infinispan.remote.java-serial-whitelist=your_marshalled_beans_package.* 
    2
1
使用 Java Serialization Marshaller。
2
将您的类添加到序列化白名单中,以便 Data Grid marshalls 您的对象。您可以指定以逗号分隔的完全限定类名称或正则表达式列表来匹配类。

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();
}

配置 Bean

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

InfinispanRemoteCacheCustomizer Bean

@Bean
public InfinispanRemoteCacheCustomizer customizer() {
    return b -> b.tcpKeepAlive(false);
}

提示

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

3.4. 启用 Spring 缓存支持

@EnableCaching 注释添加到应用以启用 Spring Cache 支持。

当 Data Grid starter 检测到 RemoteCacheManager bean 时,它会实例化一个新的 SpringRemoteCacheManager,它提供了一个 Spring Cache 的实现。

3.5. 公开数据网格统计

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

要使用 Actuator,请在 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>

然后,您必须以编程方式或声明性激活相应缓存实例的统计信息。

以编程方式

@Bean
public InfinispanCacheConfigurer cacheConfigurer() {
  return cacheManager -> {
     final org.infinispan.configuration.cache.Configuration config =
           new ConfigurationBuilder()
                 .jmxStatistics().enable()
                 .build();

     cacheManager.defineConfiguration("my-cache", config);
  };
}

声明性

<local-cache name="my-cache" statistics="true"/>

Spring Boot Actuator registry 在应用程序启动时绑定缓存实例。如果您动态创建缓存,您应该使用 CacheMetricsRegistrar bean 将缓存绑定到 Actuator registry,如下所示:

@Autowire
CacheMetricsRegistrar cacheMetricsRegistrar;

@Autowire
CacheManager cacheManager;
...

cacheMetricsRegistrar.bindCacheToRegistry(cacheManager.getCache("my-cache"));

第 4 章 使用 Spring 会话

4.1. 启用 Spring 会话支持

Data Grid Spring Session 支持基于 SpringRemoteCacheManagerSpringEmbeddedCacheManager 构建。默认情况下,此初学者会生成这些 Bean。

要在项目中使用 Spring Session,请执行以下操作:

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

    • @EnableCaching
    • @EnableInfinispanRemoteHttpSession
    • @EnableInfinispanEmbeddedHttpSession

第 5 章 应用程序属性

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

# List Infinispan or Data Grid servers by IP address or hostname at port 11222.
infinispan.remote.server-list=127.0.0.1:11222

#
# 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.serverList =

# 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 whitelist.
#infinispan.remote.java-serial-whitelist=

法律通告

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

© 2026 Red Hat
返回顶部