跳转到正文

Store 快速开始

本页在已有 Spring Boot 应用中加入一个启动演示:写入带有效期的字符串,读取它,再完成一次原子计数。使用本地后端,无需 Redis、数据库或 Business 模块。

1. 添加依赖

当前 EFC 源码基线为 Java 25、Spring Boot 4.1.0,Component 版本为 4.1.0-SNAPSHOT。应用需要能够解析对应的 EFC 构件,并已有可正常启动的 @SpringBootApplication

尚未通过项目父 POM 或其他 BOM 管理 Component 版本时,在应用 POM 中导入:

xml
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.own</groupId>
            <artifactId>springboot-component-dependencies</artifactId>
            <version>4.1.0-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

dependencies 中添加本地 Starter:

xml
<dependency>
    <groupId>com.own.component</groupId>
    <artifactId>springboot-component-store-starter-local</artifactId>
</dependency>

已配置其他 Store 后端的应用沿用原后端;本页演示假设没有自定义 Store Bean。Starter 会提供 StoreClient、名为 storeTemplateStoreTemplate<String>、锁管理器、限流管理器和 DataCacheUtil

2. 配置命名空间

application.yml 中为演示指定独立命名空间。未配置 own.store.backend 时默认选择 local

yaml
own:
  store:
    namespace: store-demo

本地数据在当前 StoreClient 实例内共享,不会跨应用进程共享。

3. 添加启动演示

将下列类放在应用组件扫描范围内,例如启动类所在包的子包。示例使用 @Qualifier 明确选择默认字符串模板;应用添加其他模板后也不会误选。

java
package example.store;

import com.own.component.store.api.StoreTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@Configuration(proxyBeanMethods = false)
public class StoreDemoConfiguration {

    @Bean
    CommandLineRunner storeDemo(
            @Qualifier("storeTemplate") StoreTemplate<String> store) {
        return args -> {
            String key = "demo:greeting";
            store.value().set(key, "Hello EFC", Duration.ofMinutes(5));
            System.out.println("value=" + store.value().get(key));

            store.atomic().delete("demo:visits");
            long visits = store.atomic().incrementAndGet(
                    "demo:visits", Duration.ofMinutes(5));
            System.out.println("visits=" + visits);

            System.out.println("deleted=" + store.value().delete(key));
            System.out.println("missing=" + store.value().get(key));
            store.atomic().delete("demo:visits");
        };
    }
}

4. 启动并核对结果

通过应用原有启动方式运行 @SpringBootApplication 主类。CommandLineRunner 在容器启动后执行一次,控制台应出现:

text
value=Hello EFC
visits=1
deleted=true
missing=null

字符串与计数属于不同的数据类型空间;示例执行后主动清理了两条演示数据。本地 Store 不持久化,实际应用也不能把“没有 TTL”理解为数据永不丢失。

如果没有创建 storeTemplate,先确认引入了运行时 Starter、后端选择与依赖匹配,以及是否有自定义 Bean 改变了装配条件。详细说明见自动配置与覆盖

接下来可使用查询结果缓存包装已有查询,或按Redis 后端切换到多个实例共享的数据与锁。