Вопрос

In our company we can have a machine hostname as -

dbx111.dc1.host.com
dbx112.dc2.host.com
dcx113.dc3.host.com

Here dc1, dc2, dc3 are our datacenter and we will be having only three datacenter for now. And also it might be possible that machine hostname can have more dots in between separated by another domain in future.

Now I need to find out which datacenter my current machine is in as I will be running below code on the actual machine. If my machine is in DC1 then I need to return /zk/dc1 but if my machine is in DC2 then I need to return /zk/dc2 and if my machine is in DC3 then I would return /zk/dc3.

But if my machine datacenter is in DEV, then I would randomly return either /zk/dc1 or /zk/dc2.

Currently my below code only writtens, in which DATACENTER I am in such as whether it is either DC1 or DC2 or DC3 or DEV. But I am not sure how to add the above logic as well in this ENUM so that it can also return me /zk/dc1 or /zk/dc2 or /zk/dc3 depending on which datacenter I am in.

And also if I just need to get only which Datacenter I am in, then it should be able to work that way as well.

public static void main(String[] args) {
        System.out.println(DatacenterEnum.getCurrentDatacenter());
}

public enum DatacenterEnum {

    DEV, DC1, DC2, DC3;

    public static String forCode(int code) {
    return (code >= 0 && code < values().length) ? values()[code].name() : null;
    }

    private static final DatacenterEnum ourlocation = compareLocation();

    private static DatacenterEnum compareLocation() {
    String ourhost = getHostName();
    for (DatacenterEnum dc : values()) {
        String namepart = "." + dc.name().toLowerCase() + ".";
        if (ourhost.indexOf(namepart) >= 0) {
        return dc;
        }
    }
    return null;
    }

    private static final String getHostName() {
    try {
        return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
    } catch (UnknownHostException e) {      
        //log error
    }
    return null;
    }

    public static DatacenterEnum getCurrentDatacenter() {
    return ourlocation;
    }       
}

Any idea how this can be done efficiently?

Это было полезно?

Решение

private void toZkString() {
    if (this == DEV) {
        return new Random().nextBoolean() ? "/zk/dc1" : "/zk/dc2";
    }
    return "/zk/" + name().toLowercase();
}

private static final String OUR_LOCATION_AS_ZK_STRING = ourlocation.toZkString();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top