Spring Boot应用程序集成etcd

以下是一个Spring Boot应用程序,集成etcd实现键值存储和查询的示例。我们将使用etcd提供的Java客户端jetcd来与etcd进行交互。

docker compose 安装 etcd

使用docker compose 安装并启动 etcd:

etcd-compose.yml 文件内容:

version: '3.5'

services:
  etcd:
    container_name: milvus-etcd
    image: quay.io/coreos/etcd:v3.5.5
    environment:
      - ETCD_AUTO_COMPACTION_MODE=revision
      - ETCD_AUTO_COMPACTION_RETENTION=1000
      - ETCD_QUOTA_BACKEND_BYTES=4294967296
      - ETCD_SNAPSHOT_COUNT=50000
    ports:
      - "2379:2379"
    volumes:
      - ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/etcd:/etcd
    command: etcd -advertise-client-urls=http://127.0.0.1:2379 -listen-client-urls http://0.0.0.0:2379 --data-dir /etcd
    healthcheck:
      test: ["CMD", "etcdctl", "endpoint", "health"]
      interval: 30s
      timeout: 20s
      retries: 3

启动容器:

docker compose -f etcd-compose.yml up -d

创建Spring Boot项目

首先,确保你在项目的pom.xml文件中添加了以下依赖:

    <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Jetcd Java Client for etcd -->
        <!-- https://mvnrepository.com/artifact/io.etcd/jetcd-core -->
        <dependency>
            <groupId>io.etcd</groupId>
            <artifactId>jetcd-core</artifactId>
            <version>0.5.11</version>
        </dependency>

        <!-- Lombok (可选) -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.12.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

配置etcd连接

application.properties文件中添加etcd相关的配置:

etcd.endpoints=http://localhost:2379

创建配置类

创建一个配置类来定义etcd客户端:

package com.example.etcddemo.config;

import io.etcd.jetcd.Client;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EtcdConfig {

    @Value("${etcd.endpoints}")
    private String etcdEndpoints;

    @Bean
    public Client etcdClient() {
        return Client.builder().endpoints(etcdEndpoints.split(",")).build();
    }
}

创建服务层

创建一个服务层来封装业务逻辑:

package com.example.etcddemo.service;

import io.etcd.jetcd.ByteSequence;
import io.etcd.jetcd.Client;
import io.etcd.jetcd.kv.GetResponse;
import io.etcd.jetcd.kv.PutResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;

@Service
@RequiredArgsConstructor
public class EtcdService {

    private final Client etcdClient;

    public CompletableFuture<PutResponse> putValue(String key, String value) {
        ByteSequence keyByte = ByteSequence.from(key, StandardCharsets.UTF_8);
        ByteSequence valueByte = ByteSequence.from(value, StandardCharsets.UTF_8);

        return etcdClient.getKVClient().put(keyByte, valueByte);
    }

    public CompletableFuture<String> getValue(String key) {
        ByteSequence keyByte = ByteSequence.from(key, StandardCharsets.UTF_8);
        CompletableFuture<GetResponse> getFuture = etcdClient.getKVClient().get(keyByte);

        return getFuture.thenApply(getResponse -> {
            if (getResponse.getKvs().isEmpty()) {
                return null;
            }
            return getResponse.getKvs().get(0).getValue().toString(StandardCharsets.UTF_8);
        });
    }

    public CompletableFuture<Void> deleteValue(String key) {
        ByteSequence keyByte = ByteSequence.from(key, StandardCharsets.UTF_8);
        return etcdClient.getKVClient().delete(keyByte).thenAccept(deleteResponse -> {});
    }
}

创建控制器

创建一个控制器来处理HTTP请求:

package com.example.etcddemo.controller;

import com.example.etcddemo.service.EtcdService;
import io.etcd.jetcd.kv.PutResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/etcd")
@RequiredArgsConstructor
public class EtcdController {

    private final EtcdService etcdService;

    @PostMapping("/put")
    public CompletableFuture<PutResponse> putValue(@RequestParam String key, @RequestParam String value) {
        return etcdService.putValue(key, value);
    }

    @GetMapping("/get")
    public CompletableFuture<String> getValue(@RequestParam String key) {
        return etcdService.getValue(key);
    }

    @DeleteMapping("/delete")
    public CompletableFuture<Void> deleteValue(@RequestParam String key) {
        return etcdService.deleteValue(key);
    }
}

Spring Boot 主类

创建Spring Boot应用程序的主类:

package com.example.etcddemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EtcdDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(EtcdDemoApplication.class, args);
    }
}

运行应用程序

启动Spring Boot应用程序。你可以使用Postman或其他HTTP客户端来测试API:

  • 存储数据

    POST http://localhost:8080/etcd/put
    Params: 
    - key: myKey
    - value: myValue
    
  • 查询数据

    GET http://localhost:8080/etcd/get
    Params: 
    - key: myKey
    
  • 删除数据

    DELETE http://localhost:8080/etcd/delete
    Params: 
    - key: myKey
    

解释

  1. 依赖管理

    • 使用Spring Boot Starter Web简化Web应用开发。
    • 使用Jetcd Java客户端来与etcd进行交互。
  2. 配置

    • application.properties中指定etcd服务器的地址。
  3. 配置类

    • 定义etcd Client bean用于与etcd进行交互。
  4. 服务层

    • 封装业务逻辑,提供数据存储、查询和删除的高层接口。
  5. 控制器

    • 处理HTTP请求,提供RESTful API进行数据存储、查询和删除。

通过这个示例,你可以轻松地使用Spring Boot集成etcd来实现键值数据的存储和查询功能。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值