Java实现consul配置读取

文章目录


前言

实现一个快速读取consul配置的工具类。

代码

使用时直接调用枚举的 defaultValueIfNull() 方法即可

import com.google.gson.reflect.TypeToken;
import com.idiudiu.common.model.LoginRequest;
import com.idiudiu.common.utils.ConsulUtil;
import com.idiudiu.common.utils.GsonUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

@Getter
public enum ConsulConfig {
    TEST_INT("test/int", 100, TypeToken.get(Integer.class).getType()),
    TEST_DOUBLE("test/double", 100, TypeToken.get(Integer.class).getType()),
    TEST_BOOL("test/bool", false, TypeToken.get(Boolean.class).getType()),
    TEST_STRING("test/string", "test", TypeToken.get(String.class).getType()),
    TEST_LIST("test/list", null, new TypeToken<List<Integer>>(){}.getType()),
    TEST_MAP("test/map", null, new TypeToken<Map<Integer, String>>(){}.getType()),
    TEST_MAP2("test/map2", null, new TypeToken<Map<Integer, Map<String, Double>>>(){}.getType()),
    TEST_JSON("test/json", null, TypeToken.get(LoginRequest.class).getType()),
    ;

    private final String key;
    private final Object defaultValue;
    private final Type type;

    ConsulConfig(String key, Object defaultValue, Type type) {
        this.key = key;
        this.defaultValue = defaultValue;
        this.type = type;
    }

    @SuppressWarnings("unchecked")
    public <T> T defaultValueIfNull() {
        String config = ConsulUtil.getConfig(key);
        if (config == null) {
            return (T) defaultValue;
        }
        if ("java.lang.String".equals(type.getTypeName())) {
            return (T) config;
        }
        return GsonUtil.convert2Object(config, type);
    }
}
import com.google.common.collect.Maps;
import com.google.gson.reflect.TypeToken;
import com.idiudiu.common.config.ConsulConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

@Slf4j
public class ConsulUtil {
    private static final String KV_URL = "http://localhost:8500/v1/kv/";


    private static Map<String, String> getRequestHeader() {
        Map<String, String> header = Maps.newHashMap();
        header.put("Accept", "application/json");
        header.put("Content-Type", "application/json");
        return header;
    }

    public static String getConfig(String key) {
        try {
            String url = KV_URL + key;
            String response = HttpClientUtil.sendHttpGet(url, null, getRequestHeader());
            log.info("getConfig key: {}, response: {}", key, response);
            List<Map<String, Object>> results = GsonUtil.convert2Object(response, new TypeToken<List<Map<String, Object>>>() {
            }.getType());
            if (CollectionUtil.isEmpty(results) || ObjectUtils.isEmpty(results.get(0).get("Value"))) {
                return null;
            }
            return Base64Util.decoder(results.get(0).get("Value").toString());
        } catch (Exception e) {
            log.error("getConfig error: ", e);
        }
        return null;
    }

    public static boolean addConfig(String key, String value) {
        try {
            String url = KV_URL + key;
            String response = HttpClientUtil.sendHttpPut(url, value, getRequestHeader());
            log.info("addConfig key: {}, value: {}, response: {}", key, value, response);
            return StringUtils.equals(response, "true");
        } catch (Exception e) {
            log.error("addConfig error: ", e);
        }
        return false;
    }

    public static boolean updateConfig(String key, String value) {
        try {
            String url = KV_URL + key;
            String response = HttpClientUtil.sendHttpPut(url, value, getRequestHeader());
            log.info("updateConfig key: {}, value: {}, response: {}", key, value, response);
            return StringUtils.equals(response, "true");
        } catch (Exception e) {
            log.error("updateConfig error: ", e);
        }
        return false;
    }

    public static boolean deleteConfig(String key) {
        try {
            String url = KV_URL + key;
            String response = HttpClientUtil.sendHttpDelete(url, getRequestHeader());
            log.info("deleteConfig key: {}, response: {}", key, response);
            return StringUtils.equals(response, "true");
        } catch (Exception e) {
            log.error("deleteConfig error: ", e);
        }
        return false;
    }

    public static void main(String[] args) {
        // System.out.println(deleteConfig("test/long2"));
        Map<Integer, Map<String, Double>> a = ConsulConfig.TEST_MAP2.defaultValueIfNull();
        System.out.println(a);
    }
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

public class GsonUtil {
    private static final Gson GSON = new GsonBuilder().enableComplexMapKeySerialization().create();


    public static String dump2JsonString(Object object) {
        return GSON.toJson(object);
    }

    public static Object convert2Object(String s) {
        return GSON.fromJson(s, Object.class);
    }

    public static <T> T convert2Object(String s, Type type) {
        return GSON.fromJson(s, type);
    }

    public static <T> T convert2Object(String s, Class<T> aclass) {
        return GSON.fromJson(s, aclass);
    }

    public static <T> T deepCopy(T object, Type type) {
        return convert2Object(dump2JsonString(object), type);
    }
}
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用Java API读取Consul配置节点的数据,您可以按照以下步骤: 1. 创建Consul客户端:您需要使用Consul.Builder类创建Consul客户端。您可以指定Consul服务器的IP地址,端口号等信息。 ```java Consul client = Consul.builder() .withUrl("http://localhost:8500") .build(); ``` 2. 读取配置节点的数据:您需要使用KeyValueClient类获取Consul配置节点的数据。例如,要获取名为“my-config”的配置节点的值,您可以使用以下代码: ```java KeyValueClient keyValueClient = client.keyValueClient(); String value = keyValueClient.getValueAsString("my-config").get(); System.out.println("Value of my-config: " + value); ``` 这将返回名为“my-config”的配置节点的值。 3. 检查节点是否存在:在读取节点的值之前,您可能需要检查该节点是否存在。您可以使用以下代码检查节点是否存在: ```java boolean isExist = keyValueClient.getKeys("my-config").getResponse().contains("my-config"); if (isExist) { String value = keyValueClient.getValueAsString("my-config").get(); System.out.println("Value of my-config: " + value); } else { System.out.println("Node my-config does not exist!"); } ``` 这将检查名为“my-config”的节点是否存在。如果存在,则返回该节点的值,否则打印出“Node my-config does not exist!”的信息。 这是一个简单的示例,您可以使用Consul API读取更多配置节点的数据,例如获取多个节点的值等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值