天天看点

java ddns_简单ddns的实现

coredns +

packageorg.rx.service;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importlombok.RequiredArgsConstructor;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.io.FileUtils;importorg.rx.common.AppConfig;importorg.rx.core.Tasks;importorg.rx.net.http.HttpClient;importorg.springframework.stereotype.Service;importjavax.annotation.PostConstruct;importjava.nio.charset.StandardCharsets;import staticorg.rx.core.Contract.eq;import staticorg.rx.core.Contract.quietly;

@Slf4j

@Service

@RequiredArgsConstructorpublic classScheduleService {private finalAppConfig config;private volatileString lastIp;

@PostConstructpublic voidinit() {

Tasks.schedule(()->{

HttpClient client= newHttpClient();

quietly(()->{

String url= "https://api.myip.com";

JSONObject json=JSON.parseObject(client.get(url));if (!eq(lastIp = json.getString("ip"), lastIp)) {

log.info("refresh dns db");

FileUtils.writeStringToFile(config.getDnsDb(), String.format("f-li.cn.\t\tIN\tSOA dns.f-li.cn. rx.f-li.cn. 2020020414 7200 3600 1209600 3600\n" +

"cloud.f-li.cn.\tIN\tA\t103.126.103.83\n" +

"v.f-li.cn.\t\tIN\tA\t%s\n", lastIp), StandardCharsets.UTF_8, false);

}

});

}, config.getJobDelaySeconds()* 1000);

}

}

package org.rx.service;

import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.apache.commons.io.FileUtils;import org.rx.common.AppConfig;import org.rx.core.Tasks;import org.rx.net.http.HttpClient;import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

import java.nio.charset.StandardCharsets;

import static org.rx.core.Contract.eq;import static org.rx.core.Contract.quietly;

@[email protected]@RequiredArgsConstructorpublic class ScheduleService {    private final AppConfig config;    private volatile String lastIp;

@PostConstruct    public void init() {        Tasks.schedule(() -> {            HttpClient client = new HttpClient();

quietly(() -> {                String url = "https://api.myip.com";                JSONObject json = JSON.parseObject(client.get(url));                if (!eq(lastIp = json.getString("ip"), lastIp)) {                    log.info("refresh dns db");                    FileUtils.writeStringToFile(config.getDnsDb(), String.format("f-li.cn.\t\tIN\tSOA dns.f-li.cn. rx.f-li.cn. 2020020414 7200 3600 1209600 3600\n" +                            "cloud.f-li.cn.\tIN\tA\t103.126.103.83\n" +                            "v.f-li.cn.\t\tIN\tA\t%s\n", lastIp), StandardCharsets.UTF_8, false);                }            });        }, config.getJobDelaySeconds() * 1000);    }}