Signed-off-by: Cao Xueliang caoxl78320@163.com --- src/lib/constants.cr | 8 +++++++ src/lib/etcd_client.cr | 51 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 src/lib/constants.cr create mode 100644 src/lib/etcd_client.cr
diff --git a/src/lib/constants.cr b/src/lib/constants.cr new file mode 100644 index 0000000..d6a96d7 --- /dev/null +++ b/src/lib/constants.cr @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: MulanPSL-2.0+ or GPL-2.0 +# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved. + +BASE = "/queues" + +ETCD_HOST = "172.17.0.1" +ETCD_PORT = 2379 +ETCD_VERSION = "v3beta" diff --git a/src/lib/etcd_client.cr b/src/lib/etcd_client.cr new file mode 100644 index 0000000..637b738 --- /dev/null +++ b/src/lib/etcd_client.cr @@ -0,0 +1,51 @@ +# SPDX-License-Identifier: MulanPSL-2.0+ or GPL-2.0 +# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved. + +require "etcd" + +require "./constants" + +class EtcdClient + def initialize + host = (ENV.has_key?("ETCD_HOST") ? ENV["ETCD_HOST"] : ETCD_HOST) + port = (ENV.has_key?("ETCD_PORT") ? ENV["ETCD_PORT"].to_i32 : ETCD_PORT) + version = (ENV.has_key?("ETCD_VERSION") ? ENV["ETCD_VERSION"] : ETCD_VERSION) + @etcd = Etcd.client(host, port, version) + end + + def put(queue, content) + queue = "#{BASE}/#{queue}" unless queue.starts_with?(BASE) + @etcd.kv.put_not_exists(queue, content) + end + + def delete(queue) + queue = "#{BASE}/#{queue}" unless queue.starts_with?(BASE) + @etcd.kv.delete(queue) + end + + def range(queue) + queue = "#{BASE}/#{queue}" unless queue.starts_with?(BASE) + @etcd.kv.range(queue) + end + + def range_prefix(prefix) + prefix = "#{BASE}/#{prefix}" unless prefix.starts_with?(BASE) + @etcd.kv.range_prefix(prefix) + end + + def update(queue, value) + queue = "#{BASE}/#{queue}" unless queue.starts_with?(BASE) + @etcd.kv.put(queue, value) + end + + def move(f_queue, t_queue, value) + @etcd.kv.move(f_queue, t_queue, value) + end + + def watch_prefix(prefix, **opts, &block : Array(Etcd::Model::WatchEvent) -> Void) + prefix = "#{BASE}/#{prefix}" unless prefix.starts_with?(BASE) + @etcd.watch.watch_prefix(prefix, **opts, &block) + end + +end +