Yerleşik önbellek ile güvenilir etki alanı adı çözümlemesi sağlamak amacıyla HTTPDNS Android SDK'sını uygulamanıza entegre edin.
Genel bakış
Android SDK, HTTPDNS DoH JSON API için bir Java sarmalayıcısıdır. Android uygulamalarının etki alanı adlarını çözümlemesi için Java arayüzleri sunar ve Time-to-Live (TTL) ile Least Recently Used (LRU) ilkelerini kullanan verimli bir yerel önbellek içerir. Etki alanı adı çözümleme hatalarını gidermek ve hassas, düşük maliyetli zamanlama özelliğini etkinleştirmek amacıyla HTTPDNS hizmetini Android uygulamanıza entegre edebilirsiniz.
Temel avantajlar şunlardır:
-
Kullanımı basittir
HTTPDNS hizmetine erişmek için minimum düzeyde kod yazmanız yeterlidir.
-
Sıfır gecikme süresi
LRU önbelleği, çözümlenen IP adreslerini yerel olarak depolar ve TTL süresi dolmadan önce girdileri proaktif olarak yeniler; bu sayede sıfır gecikme süresiyle çözümleme gerçekleştirilir.
Çalışan bir uygulama referansı için alidns_android_demo örnek projesini indirin.
SDK entegrasyonu
SDK'yı ekleyin
Gradle ve Maven
Aşağıdaki kodu build.gradle dosyanıza ekleyin:
allprojects {
repositories {
maven {
url 'https://maven.aliyun.com/repository/public/'
}
mavenLocal()
mavenCentral()
}
}
Bağımlılık bilgilerini ekleyin:
dependencies {
implementation 'com.alibaba.pdns:alidns-android-sdk:2.3.3'
implementation 'com.google.code.gson:gson:2.8.5'
}
AAR dosyası
SDK'yı SDK'yı İndirin sayfasından indirin, ardından alidns_android_sdk.aar paketini projenizin libs dizinine ekleyin.
SDK başlatma
Çözümleme hatalarını önlemek için SDK'yı uygulama yaşam döngünüzün mümkün olan en erken aşamasında başlatın.
Konsoldan Account ID bilginizi alın ve anahtar oluşturun işlemiyle AccessKey ID ve AccessKey Secret değerlerinizi edinin. Ardından SDK'yı aşağıdaki Application sınıfı örneğinde gösterildiği şekilde başlatın:
public class DnsCacheApplication extends Application{
private String accountId = "Your Account ID"; // Set your Account ID from the console.
private String accessKeyId = "Your AccessKey ID"; // Set your AccessKey ID from the console.
private String accessKeySecret = "Your AccessKey Secret"; // Set your AccessKey Secret from the console.
@Override
public void onCreate() {
super.onCreate();
// Set the Account ID, AccessKey ID, and AccessKey Secret for SDK access.
DNSResolver.Init(this, accountId, accessKeyId, accessKeySecret);
// Note: If you configure domains for keep-alive, resolution is automatically triggered when 75% of the TTL elapses.
// This ensures that resolution for these domains always hits the cache. However, if you use a CDN,
// the TTL can be short, leading to frequent requests and increased costs. Use this method with caution.
DNSResolver.setKeepAliveDomains(new String[]{"your-domain-to-keep-alive-1","your-domain-to-keep-alive-2",...});
// Perform pre-resolution for specified domains to get IPv4 addresses. Replace the placeholder domains with the ones you want to resolve.
DNSResolver.getInstance().preLoadDomains(DNSResolver.QTYPE_IPV4,new String[]{"your-domain-to-preload-1","your-domain-to-preload-2",...});
}
}
DNSResolver, HTTPDNS SDK'sının çekirdek sınıfıdır. Alan adlarını IP adreslerine çözümlemek için HTTPDNS DoH JSON API'sini sarmalar. HTTPDNS SDK'sını Application alt sınıfınızda başlatın.
Aşağıdaki izinleri AndroidManifest.xml dosyasında bildirin:
<!--Required permissions-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
SDK kimlik doğrulama
SDK, yetkisiz kullanımı önlemek amacıyla 2.0 sürümünden itibaren kimlik doğrulama gerektirir. HTTPDNS'i etkinleştirmek için konsolda anahtar oluşturun ve bir AccessKey ID ile AccessKey Secret elde edin. Kimlik doğrulama parametrelerini SDK başlatma sırasında ayarlamanız gerekir. HTTPDNS, kimliği doğrulanmamış istekleri reddeder; bu durum çözümlemenin başarısız olmasına ve hizmetlerinizi etkilemesine neden olur.HTTPDNS
Kimlik doğrulama parametrelerini aşağıdaki gibi ayarlayabilirsiniz:
DNSResolver.Init(this, accountId, accessKeyId, accessKeySecret);
Account ID, AccessKey ID, AccessKey Secret veya diğer çalışma zamanı verilerinizin günlüklerde açığa çıkmasını önlemek için üretim sürümünüzde SDK hata ayıklama günlük kaydını devre dışı bırakın.
SDK entegrasyonu, kodunuzda Account ID, AccessKey ID ve AccessKey Secret değerlerinin ayarlanmasını gerektirir. Bu parametreler ölçümleme ve faturalama ile bağlantılıdır. Kötü niyetli tersine mühendislik işlemlerinin kimlik bilgilerinizi ortaya çıkarmasını önlemek için uygulamanızı yayınlamadan önce kod karartma ve uygulama güçlendirme özelliklerini etkinleştirin.
SDK entegrasyon sorunları
"Cleartext HTTP traffic not permitted" hatası
"Didn't find class BasicHttpParams" hatası
NDK yapılandırması
API referansı
Ortak ayarlar
1. Init yöntemini kullanarak başlatma
SDK'yı Application sınıfınızda başlatırken Init yöntemini çağırın.
DNSResolver.Init(this, accountId, accessKeyId, accessKeySecret);
2. Ön çözümleme için alan adlarını ayarlama
Ön çözümlemeyi etkinleştirmek ve sonraki gecikme sürelerini azaltmak için başlatma sırasında alan adlarını HTTPDNS SDK'sına kaydedin:
IPv4 veya IPv6 alan adları için ön çözümlemeyi belirtin
// Specify the record type for pre-resolution. Replace the placeholder domains with the ones you want to resolve.
DNSResolver.getInstance().preLoadDomains(DNSResolver.QTYPE_IPV4,new String[]{...});
// DNSResolver.QTYPE_IPV4: Pre-fetches the IPv4 record type for the domain.
// DNSResolver.QTYPE_IPV6: Pre-fetches the IPv6 record type for the domain.
// DNSResolver.QTYPE_IPV4_IPV6: Pre-fetches both IPv4 and IPv6 record types for the domain.
Mevcut ağa göre IPv4 veya IPv6'yı ön çözümleme için otomatik olarak seçin. Çift yığın ortamında hem IPv4 hem de IPv6 adresleri önceden yüklenir.
DNSResolver.getInstance().preLoadDomains(domains);
Ön çözümleme API'si, gerçek zamanlı olarak eşzamansız ağ isteklerini tetikler. Bu API'yi çağırmadan önce gerekli tüm başlatma işlemlerinin tamamlandığından emin olun.
3. Önbellek canlı tutma için alan adlarını ayarlama
SDK, önbelleğin güncel kalmasını sağlamak üzere yapılandırılan alan adlarını TTL süresinin %75'i dolduğunda yeniden çözümler. Bu işlemi 10 alan adı ile sınırlamanızı öneririz. Ön çözümlemeden bağımsızdır.
DNSResolver.setKeepAliveDomains(new String[]{"your-domain-1", "your-domain-2"});
Avantajlar
Kayıtlar zamanında güncellenir (TTL sona ermeden önce).
Ön çözümleme ile birlikte kullanıldığında, ilk çözümleme gecikme süresi 0 ms'ye düşürülebilir.
Dezavantajlar
TTL'nin %75'inde yeniden istek göndermek ek maliyetlere neden olur.
4. IPv6 sunucu adresi kullanılıp kullanılmayacağını belirtme
HTTPDNS hizmeti hem IPv4 hem de IPv6 erişimini destekler. IPv6 sunucu erişimini değiştirmek için DNSResolver.setEnableIPv6(boolean enable) kullanın. Varsayılan: IPv4. IPv6 etkinleştirilirse ve HTTPDNS hizmetine bağlantı başarısız olursa, SDK otomatik olarak IPv4 üzerinden bir kez yeniden dener.
5. Maksimum önbellek girişi sayısını ayarlama
DNSResolver.getInstance().setMaxCacheSize(CACHE_MAX_NUMBER); // Sets the maximum number of cache entries. The default is 100.
Maksimum count değerini özelleştirebilirsiniz.
6. Sunucu erişimi için protokolü ayarlama
SDK, çözümleme istekleri için HTTP ve HTTPS protokollerini destekler. Varsayılan: HTTPS (güvenlik açısından önerilir). HTTPS isteklerinin HTTP oranının beş katı ücretlendirildiğini unutmayın. İş gereksinimlerinize göre seçim yapın.HTTPDNS
DNSResolver.setSchemaType(DNSResolver.HTTPS); // The default access mode is HTTPS.
DNSResolver.HTTP: Sunucu taraflı arabirimlere HTTP üzerinden erişir.
DNSResolver.HTTPS: Sunucu taraflı arabirimlere HTTPS üzerinden erişir.
Gelişmiş ayarlar
1. SDK hata ayıklama günlüğünü etkinleştirin veya devre dışı bırakın
DNSResolver.setEnableLogger(true); // SDK debug logs are disabled by default.
SDK hata ayıklama günlüğünü etkinleştirin veya devre dışı bırakın. Varsayılan: devre dışı.
**2. HTTPDNS çözümlemesi başarısız olduğunda yerel DNS'e otomatik yük devretmenin etkin olup olmadığını belirtin**
DNSResolver.setEnableLocalDns(true); // By default, automatic fallback to local DNS is enabled when HTTPDNS resolution fails.
3. Kısa modu etkinleştirin veya devre dışı bırakın
HTTPDNS DoH JSON API'si verileri tam JSON ve kompakt IP dizisi olmak üzere iki biçimde döndürür. Kısa modu etkinleştirmek veya devre dışı bırakmak için DNSResolver.setEnableShort(boolean enable) yöntemini çağırabilirsiniz. Varsayılan olarak kısa mod devre dışıdır.
DNSResolver.setEnableShort(true); // The default value is false. You do not need to set this parameter.
Kısa modda, HTTPDNS SDK tam JSON yerine kompakt bir IP dizisi döndürerek yanıt boyutunu azaltır. Trafik duyarlı senaryolar için uygundur.
4. Süresi dolmayan önbelleğin etkin olup olmadığını belirtin
DNSResolver.setImmutableCacheEnable(false); // By default, the non-expiring cache is disabled.
SDK üç önbellek güncelleme mekanizması sağlar:
-
Önbellek asla süresi dolmaz: Etkinleştirildiğinde bu özellik, son kullanma kontrollerini ve güncelleme işlemlerini atlayarak önbelleği uygulama çalışma süresi boyunca her zaman geçerli kabul eder. Kullanıcı çözümleme sayısını en aza indirmek için önbelleği aktif olarak güncellemek amacıyla
setKeepAliveDomainsayarlamanıza gerek kalmaz.Yöntem:
DNSResolver.setImmutableCacheEnable(boolean var0)var0parametresitrueolduğunda önbelleğin süresinin dolmaması özelliği etkinleşir.var0parametresifalseolduğunda bu özellik devre dışı kalır. -
Aktif önbellek güncellemesi: Bu özellik, çözümlemelerin en güncel önbelleğe alınmış kayıtlara isabet etmesini sağlar. Bir alan adı için yetkili alan değiştiğinde bu mekanizma, çözümleme isteklerinin hem DNS gecikme süresini azaltmak için önbelleğe isabet etmesini hem de en yeni kayıtları almasını sağlar. Bir alan adının TTL'sinin %75'i geçtiğinde SDK, önbelleği güncellemek için otomatik olarak bir çözümleme sorgusu tetikler. Aktif güncellemelerin etkinleştirildiği alan adı sayısının 10 ile sınırlanmasını öneririz.
Yöntem:
DNSResolver.setKeepAliveDomains(String[] var1)Açıklama:
var1proaktif olarak güncellenmesi gereken alan adlarını içeren bir dize dizisidir. -
Pasif önbellek güncellemesi:
Çözümleme sonuçlarını almak için aşağıdaki iki yöntemi çağırdığınızda önbellek pasif olarak güncellenir:
getIPsV4ByHost(String hostName)yöntemi belirtilenhostNameiçin bir IPv4 kayıt dizisi alır. Önbellek boş değilse ve TTL'si içindeyse yöntem önbelleğe alınmış sonucu doğrudan döndürür. Aksi takdirde önce ağ isteği yoluyla en son çözümleme sonucunu alır, ardından bu sonucu döndürür ve önbelleği günceller. Bu yöntem genellikle yüksek doğrulukta çözümleme sonuçları gerektiren senaryolarda kullanılır.-
getIpv4ByHostFromCache(String hostName, boolean isAllowExp)yöntemi bir hostName için önbellekten bir IPv4 kayıt dizisi alır. Bu yöntemisAllowExpparametresinin değerine göre önbellekten süresi dolmuş çözümleme sonuçlarının döndürülüp döndürülmeyeceğine karar verir. Uygulama başlangıcında en son çözümleme sonuçlarının önbelleğe alındığından emin olmak için bu yöntemi bir ön yükleme yöntemiyle birlikte kullanmanızı öneririz.isAllowExpdeğeritrueolarak ayarlandığında önbelleğin süresi dolmuş olsa bile eski veriler döndürülür (önbellek boşsanulldöndürülür) ve önbellek eşzamansız bir istek kullanılarak güncellenir. Bu parametrefalseolarak ayarlandığında önbelleğin süresi dolduğunda veya boş olduğundanulldöndürülür ve önbellek eşzamansız bir istek kullanılarak güncellenir.
Önerilen desen:
String[] IPArray = mDNSResolver.getIpv4ByHostFromCache(hostname,true); if (IPArray == null || IPArray.length == 0){ IPArray = mDNSResolver.getIPsV4ByHost(hostname); }
5. Önbelleği etkinleştirin veya devre dışı bırakın
DNSResolver.setEnableCache(true); // The cache is enabled by default.
Çözümleme önbelleğini etkinleştirin veya devre dışı bırakın. Varsayılan: etkin.
6. IP hız testini etkinleştirin veya devre dışı bırakın. Bu özellik 2.3.0 ve önceki sürümlerde varsayılan olarak devre dışıdır, 2.3.1 ve sonraki sürümlerde varsayılan olarak etkindir.
DNSResolver.setEnableSpeedTest(false); // Disabled by default in v2.3.0 and earlier; enabled by default in v2.3.1 and later.
IP hız testini etkinleştirin veya devre dışı bırakın. Varsayılan: v2.3.0 ve önceki sürümlerde devre dışı, v2.3.1+ sürümlerinde etkin.
7. Soket izleme yoluyla IP hız testi için bağlantı noktası numarasını ayarlayın
DNSResolver.setSpeedPort(DNSResolver.PORT_80);
Soket tabanlı IP hız testi için bağlantı noktasını ayarlayın. Varsayılan: 80.
8. IP hız testi için IPv6 tercih marjını ayarlayın (v2.3.3 ve sonraki sürümlerde desteklenir)
DNSResolver.setSpeedTestIpv6PreferMs(0);
IP hız testi için milisaniye cinsinden IPv6 tercih marjını ayarlayın. Hız testi etkinleştirildiğinde ve IPv4 ile IPv6 adresleri birlikte sıralandığında SDK, ölçülen IPv6 süresinden bu marjı düşer ve sonucu ölçülen IPv4 süresiyle karşılaştırır. Böylece IPv6, IPv4'ten marjdan daha az yavaş olsa bile tercih edilir. Varsayılan: 0 (marj devre dışı bırakılır). Geçerli aralık: [0, 1000]. Bu ayar yalnızca hız testi etkinleştirildiğinde etkili olur.
9. Alan adı önbelleğinin ISS ağına göre bölümlenip bölümlenmeyeceğini belirtin
DNSResolver.setIspEnable(true); // By default, the domain cache is partitioned by ISP network.
Etkinleştirildiğinde alan adı önbellek verileri ağ ortamı başına ayrı ayrı depolanır. Devre dışı bırakıldığında tek bir önbellek tüm ağlarda paylaşılır.
10. Negatif önbellek için maksimum TTL'yi ayarlayın
DNSResolver.setMaxNegativeCache(MAX_NEGATIVE_CACHE); // Sets the maximum TTL for the negative cache. The default is 30 seconds.
Negatif önbellek için maksimum TTL'yi ayarlayın. Bir alan adı için IP döndürülmediğinde negatif önbellek girişi oluşturulur. Varsayılan: 30 saniye.
11. Önbellek için maksimum TTL'yi ayarlayın
DNSResolver.setMaxTtlCache(MAX_TTL_CACHE); // Sets the maximum TTL for the cache. The default value is 3,600 seconds.
Önbellek girişleri için maksimum TTL üst sınırı ayarlayın. Varsayılan: 3.600 saniye.
12. İstemci alt ağ bilgilerini ayarlayın
DNSResolver.setEdnsSubnet("1.2.XX.XX/24");
setEdnsSubnet EDNS İstemci Alt Ağını (ECS, RFC 7871) destekler ve hassas trafik planlaması için kullanıcı alt ağ bilgilerini yetkili DNS'e iletir. Daha uzun bir maske daha hassas sonuçlar sağlarken daha kısa bir maske gizliliği artırır. /24 maskesi önerilir.
Bu parametre bir DNS proxy'sinin DoH JSON API'sini kullandığı senaryolar için tasarlanmıştır. Bu senaryolarda kullanıcı bir DNS sorgusunu DNS proxy'sine gönderir ve proxy bu parametreyi kullanarak kullanıcının alt ağ bilgilerini HTTPDNS üzerinden ve ardından yetkili DNS sunucusuna iletir.
Örneğin, DNSResolver.setEdnsSubnet("1.2.XX.XX/24") çağrısı yaptığınızda yetkili sunucu, bir DNS bağlantısı seçmenize yardımcı olmak için 1.2.XX.XX/24 adresine dayalı önek bilgilerini alır.
13. Alan adı çözümlemesi için zaman aşımı süresini ayarlayın
Alan adı çözümlemesi için timeout değerini ayarlayın. Varsayılan: 3 saniye. Önerilen aralık: 2–5 saniye.
DNSResolver.setTimeout(3);
14. Eşzamanlı çözümleme sayısının maksimum değerini ayarlayın (v2.3.2 ve sonraki sürümlerde desteklenir)
Eşzamanlı eşzamansız DNS çözümlemelerinin (ön çözümleme, önbellek yenileme) maksimum sayısını ayarlayın. Geçerli aralık: [1, 50]. Varsayılan: 10.
DNSResolver.setMaxConcurrentResolveCount(10);
15. Sorun giderme için SessionId'yi alın
Bir sessionId uygulama başlangıcında oluşturulur ve yaşam döngüsü boyunca sabit kalır. Tüm HTTPDNS çözümleme istekleri bu kimliği taşır. Sorun giderme amacıyla sunucudaki istekleri izlemek için bu kimliği kullanın.
public static String getSessionId()
16. Günlük çıktısı geri araması
Bu geri arama, SDK tarafından çıkarılan günlükleri alır.
HttpDnsLog.setLogger(new ILogger() {
@Override
public void log(String msg) {
Log.d("HttpDnsLogger:", msg);
}
});
ProGuard yapılandırması
-keep class com.alibaba.pdns.** {*;}
Hizmet API'si
/**
* Pre-loads domain name resolution based on the automatically detected network environment (IPv4-only, IPv6-only, or dual-stack).
* In a dual-stack network environment, both IPv4 and IPv6 resolution results are pre-loaded. You can call this method during SDK initialization at app startup.
* This method pre-stores the resolution results in the cache to reduce the latency of subsequent domain name resolutions.
*
* @param domains The domain names to be pre-loaded.
*/
public void preLoadDomains(final String[] domains)
/**
* Pre-loads domain resolution for a specified record type (IPv4 or IPv6).
* You can call this method during SDK initialization at app startup. This method pre-stores the resolution results in the cache to reduce latency for later resolutions.
*
* @param qType The record type to pre-load, such as IPv4 or IPv6.
* @param domains The domain names to be pre-loaded.
*/
public void preLoadDomains(String qType, final String[] domains)
/**
* Obtains the resolution data for the domain name based on the automatically detected network environment (IPv4-only, IPv6-only, or dual-stack).
* If a non-expired resolution result exists in the cache, the result from the cache is returned.
* If the cache is empty or the cached result has expired, a synchronous network request is sent to the server to obtain the recursive resolution result. The result is then returned and stored in the cache.
*
* @param host The domain name that you want to resolve.
* @return The optimal IP address array based on the current network environment.
*/
public String[] getIpsByHost(String host)
/**
* Obtains the array of IPv4 records that correspond to the hostname.
* If a non-expired resolution result exists in the cache, the result from the cache is returned.
* If the cache is empty or the cached result has expired, a synchronous network request is sent to the server to obtain the recursive resolution result. The result is then returned and stored in the cache.
*
* @param hostName The hostname, such as www.example.com.
* @return The array of IPv4 addresses that correspond to the hostname.
*/
public String[] getIPsV4ByHost(String hostName)
/**
* Obtains the array of IPv6 records that correspond to the hostname.
* @param hostName The hostname, such as www.example.com.
* @return The array of IPv6 addresses that correspond to the hostname.
*/
public String[] getIPsV6ByHost(String hostName)
/**
* Obtains the IP address array for the resolved domain name from the cache based on the automatically detected network environment (IPv4-only, IPv6-only, or dual-stack).
* If the cache is empty, this method returns null and initiates an asynchronous query. The query result is then stored in the cache.
* If a resolution result exists in the cache and you allow returning expired results, the expired IP addresses are returned, and the cache is updated asynchronously.
* If you do not allow returning expired results and the cached result has expired, this method returns null and then asynchronously updates the cache.
*
* @param host The host to query, such as www.example.com.
* @param isAllowExp Specifies whether to return the resolution data of an expired domain.
* @return The cached IP address array for the resolved host.
*/
public String[] getIpsByHostFromCache(String host, boolean isAllowExp)
/**
* Obtains the IP address array of the IPv4 record type for the resolved domain name from the cache.
* If the cache is empty, this method returns null and initiates an asynchronous query. The query result is then stored in the cache.
* If a resolution result exists in the cache and you allow returning expired results, the expired IP addresses are returned, and the cache is updated asynchronously.
* If you do not allow returning expired results and the cached result has expired, this method returns null and then asynchronously updates the cache.
*
* @param host The host to query, such as www.example.com.
* @param isAllowExp Specifies whether to return the resolution data of an expired domain.
* @return The IP address array of the IPv4 record type from the cache after the host is resolved.
*/
public String[] getIpv4ByHostFromCache(String host , boolean isAllowExp)
/**
* Obtains the IP address array of the IPv6 record type for the resolved domain name from the cache.
* If the cache is empty, this method returns null and initiates an asynchronous query. The query result is then stored in the cache.
* If a resolution result exists in the cache and you allow returning expired results, the expired IP addresses are returned, and the cache is updated asynchronously.
* If you do not allow returning expired results and the cached result has expired, this method returns null and then asynchronously updates the cache.
*
* @param host The host to query, such as www.example.com.
* @param isAllowExp Specifies whether to return the resolution data of an expired domain.
* @return The IP address array of the IPv6 record type from the cache after the host is resolved.
*/
public String[] getIpv6ByHostFromCache(String host , boolean isAllowExp)
/**
* Obtains the array of DomainInfo objects for IPv4 records that correspond to the URL.
* If a non-expired resolution result exists in the cache, the result from the cache is returned.
* If the cache is empty or the cached result has expired, a synchronous network request is sent to the server to obtain the recursive resolution result. The result is then returned and stored in the cache.
*
* @param url The URL, such as http://www.example.com.
* @return The array of DomainInfo objects of the IPv4 type that correspond to the URL.
*/
public DomainInfo[] getIPsV4DInfoByUrl(String url)
Note: The URL in the DomainInfo object is the URL in which the host is automatically replaced with an IP address. You do not need to manually replace the host in the URL.
/**
* Obtains the array of DomainInfo objects for IPv6 records that correspond to the URL.
* If a non-expired resolution result exists in the cache, the result from the cache is returned.
* If the cache is empty or the cached result has expired, a synchronous network request is sent to the server to obtain the recursive resolution result. The result is then returned and stored in the cache.
*
* @param url The URL, such as http://m.example.com.
* @return The array of DomainInfo objects of the IPv6 type that correspond to the URL.
*/
public DomainInfo[] getIPsV6DInfoByUrl(String url)
/**
* Obtains a DomainInfo object for the IPv4 records that correspond to a specific URL.
* If a non-expired resolution result exists in the cache, the result from the cache is returned.
* If the cache is empty or the cached result has expired, a synchronous network request is sent to the server to obtain the recursive resolution result. The result is then returned and stored in the cache.
*
* @param url The URL, such as http://m.example.com.
* @return A random DomainInfo object from the collection of IPv4-type DomainInfo objects that correspond to the URL.
*/
public DomainInfo getIPV4DInfoByUrl(String url)
/**
* Obtains a DomainInfo object for the IPv6 records that correspond to a specific URL.
* If a non-expired resolution result exists in the cache, the result from the cache is returned.
* If the cache is empty or the cached result has expired, a synchronous network request is sent to the server to obtain the recursive resolution result. The result is then returned and stored in the cache.
*
* @param url The URL, such as http://www.example.com.
* @return A random DomainInfo object from the collection of IPv6-type DomainInfo objects that correspond to the URL.
*/
public DomainInfo getIPV6DInfoByUrl(String url)
Note: The returned DomainInfo object encapsulates the following properties.
/**
* The auto-incrementing ID for the access domain.
*/
public String id = null;
/**
* The URL that can be directly used. The host in the URL is replaced with an IP address.
*/
public String url = null;
/**
* The name of the destination service to be set in the HTTP header.
*/
public String host = "";
/**
* The returned content body.
*/
public String data = null;
/**
* The time when the request starts.
*/
public String startTime = null;
/**
* The time when the request ends. If the request times out, this value is null.
*/
public String stopTime = null;
/**
* The status code returned by the server, such as 200, 404, or 500.
*/
public String code = null;
/**
* Obtains the IPv4 record that corresponds to the hostname.
* If a non-expired resolution result exists in the cache, the result from the cache is returned.
* If the cache is empty or the cached result has expired, a synchronous network request is sent to the server to obtain the recursive resolution result. The result is then returned and stored in the cache.
* @param hostName The hostname, such as www.example.com.
* @return A random IPv4 address from the set of IPv4 addresses that correspond to the hostname. If IP speed testing is enabled, the optimal IPv4 address is returned.
*/
public String getIPV4ByHost(String hostName)
/**
* Obtains the IPv6 record that corresponds to the hostname.
* If a non-expired resolution result exists in the cache, the result from the cache is returned.
* If the cache is empty or the cached result has expired, a synchronous network request is sent to the server to obtain the recursive resolution result. The result is then returned and stored in the cache.
* @param hostName The hostname, such as www.example.com.
* @return A random IPv6 address from the set of IPv6 addresses that correspond to the hostname. If IP speed testing is enabled, the optimal IPv6 address is returned.
*/
public String getIPV6ByHost(String hostName)
/**
* Obtains the statistics about successful and failed HTTPDNS requests.
*
* @return A JSON array string of the resolution statistics for all domain names.
*/
public String getRequestReportInfo()
/**
* Sets domain names for cache keep-alive. The resolution of a configured domain name is automatically initiated when 75% of the TTL elapses. This ensures that resolution requests for the configured domain name always hit the cache and improves the resolution efficiency of the SDK.
* We recommend that you do not configure an excessive number of domain names for this feature. The current limit is 10 domain names. This feature is configured independently of the pre-resolution feature.
*
* @param persistentCacheDomains
*/
public synchronized static void setKeepAliveDomains(String[] persistentCacheDomains) {
/**
* Clears the cache for specified domain names. If the hostname is null, the cache for all domain names is cleared.
*
* @param domains The array of domain names whose cache you want to clear.
*/
public void clearHostCache(String[] domains){
API örnekleri
URL: İletilen erişim adresi; örneğin, http://www.example.com.
String hostname = "www.taobao.com";
String url = "http://www.taobao.com";
1. Mevcut ağ ortamı için en uygun IP verilerini alın
String[] ip = DNSResolver.getInstance().getIpsByHost(hostname); // Gets the optimal domain resolution IP for the current network.
2. Mevcut ağ ortamına göre alan adı çözümlemesini önceden yükleyin
DNSResolver.getInstance().preLoadDomains(domains); // Sets domain names for pre-resolution. Replace the placeholder domains with the ones you want HTTPDNS to resolve.
3. Mevcut ağ ortamına göre önbellekten alan adı çözümleme verilerini okuyun
String[] ip = DNSResolver.getInstance().getIpsByHostFromCache(hostname,true); // Gets domain resolution data from the cache for the current network environment.
4. Bir IPv4 adresi alın
String IPV4 = DNSResolver.getInstance().getIPV4ByHost(hostname); // Gets the resolved IPv4 address.
5. Bir IPv6 adresi alın
String IPV6 = DNSResolver.getInstance().getIPV6ByHost(hostname); // Gets the resolved IPv6 address.
6. Önbellekten çözümlenmiş bir IPv4 adresi alın
String[] IPV4 = DNSResolver.getInstance().getIpv4ByHostFromCache(hostname , true); // Gets the resolved IPv4 address from the cache.
7. Önbellekten çözümlenmiş bir IPv6 adresi alın
String[] IPV6 = DNSResolver.getInstance().getIpv6ByHostFromCache(hostname , true); // Gets the resolved IPv6 address from the cache.
8. Bir URL'ye karşılık gelen DomainInfo nesnesini alın
DomainInfo dinfo = DNSResolver.getInstance().getIPV4DInfoByUrl(url); // Gets the replaced URL.
9. Belirtilen bir alan adının çözümleme sonucunu önbellekten temizleyin
DNSResolver.getInstance().clearHostCache(hostName); // Clears the cache for a specified domain. If hostName is set to null, the cache for all domains is cleared.
10. Başarılı ve başarısız HTTPDNS isteklerine ilişkin istatistikleri alın
String reportInfo = DNSResolver.getInstance().getRequestReportInfo(); // Gets statistics about successful and failed requests.
Aşağıdaki tabloda, alan adı çözümleme istatistiklerinin JSON dizi dizisindeki alanlar açıklanmaktadır.
[
{
"avgRtt":"1", // Average domain resolution time, in milliseconds (ms).
"degradeLocalDnsCount": 0, // Number of fallbacks to local DNS.
"domainName":"www.example.com", // The resolved domain name.
"hitDnsCacheCount": 1, // Number of cache hits.
"httpabnormalCount": 0, // Number of failed recursive requests.
"isp": "China Mobile", // ISP name.
"localDnsResolveErrCount": 0, // Number of local DNS resolution failures.
"maxRtt": 8.0, // Maximum domain resolution time, in milliseconds (ms).
"nonetworkCount": 0, // Number of times the network is unavailable.
"permissionErrCount": 0, // Number of user authentication failures.
"queryType": 1, // IP type. 1 indicates IPv4, and 28 indicates IPv6.
"recursiveReqCount": 1, // Number of recursive queries.
"reqParameterErrCount": 0, // Number of request parameter format errors.
"reqPathErrCount": 0, // Number of URL errors.
"reqServerErrCount": 0, // Number of DNS server-side errors.
"reqTimeoutCount": 0, // Number of DNS service timeout errors.
"resolveSuccessCount": 1, // Number of successful resolutions.
"timeoutCount": 0, // Number of network timeout errors.
"utfNetWorkErroNum": 0 // Number of data reporting timeout errors.
}
......
]
HTTPDNS alan adı çözümleme isteklerine ilişkin istatistikler ağ ortamı, alan adı ve istek türüne göre toplanır.
Örnek
public class MainActivity extends AppCompatActivity {
private Button button;
private TextView tvInfo;
private TextView tvResult;
private String hostUrl = "http://www.taobao.com"; // Replace this with the hostUrl that you want to resolve.
private String hostName = "www.taobao.com"; // Replace this with the hostName that you want to resolve.
private static final String TAG = "PDnsDemo";
private static ExecutorService pool = Executors.newSingleThreadExecutor();
private static final String PDNS_RESULT = "pdns_result";
private static final int SHOW_CONSOLE_TEXT = 10000;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_activity_main);
init();
initHandler();
}
private void init() {
tvInfo = findViewById(R.id.tv_respons_info);
tvResult = findViewById(R.id.tv_respons);
button = findViewById(R.id.btn_onclik);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
// Call the getIPV4ByHost method in the HTTPDNS SDK to obtain the resolved IP address of the target domain name.
String ip = DNSResolver.getInstance().getIPV4ByHost(hostName);
if(ip != null){
tvInfo.setText("The resolved IP for the domain is: "+ ip);
}
// Call the getIPV4DInfoByUrl method in the HTTPDNS SDK to get the URL from the resolved DomainInfo object.
// The host in this URL is replaced with the IP address.
DomainInfo dinfo = DNSResolver.getInstance().getIPV4DInfoByUrl(hostUrl);
if (dinfo != null) {
showResponse(dinfo);
}
}
}).start();
}
});
}
private void initHandler() {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_CONSOLE_TEXT:
tvResult.setText(msg.getData().getString(PDNS_RESULT) + "\n");
break;
}
}
};
}
private void showResponse(final DomainInfo dinfo) {
// Sends a network request.
String requestUrl = dinfo.url;
HttpURLConnection conn = null;
try {
URL url = new URL(requestUrl);
conn = (HttpURLConnection) url.openConnection();
// When you use an IP address for access, you must set the Host field of the HTTP request header to the original domain name.
conn.setRequestProperty("Host", url.getHost()); // Sets the Host field of the HTTP request header.
DataInputStream dis = new DataInputStream(conn.getInputStream());
int len;
byte[] buff = new byte[4096];
StringBuilder response = new StringBuilder();
while ((len = dis.read(buff)) != -1) {
response.append(new String(buff, 0, len));
}
Log.d(TAG, "Response: " + response.toString());
dis.close();
sendMessage(response.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (conn != null) {
conn.disconnect();
}
}
}
private void sendMessage(String message) {
if (mHandler != null) {
Message msg = mHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString(PDNS_RESULT, message);
msg.setData(bundle);
msg.what = SHOW_CONSOLE_TEXT;
mHandler.sendMessage(msg);
}
}
}
public class DnsCacheApplication extends Application {
private String accountId = "Your Account ID"; // Set your Account ID from the console.
private String accessKeyId = "Your AccessKey ID"; // Set your AccessKey ID from the console.
private String accessKeySecret = "Your AccessKey Secret"; // Set your AccessKey Secret from the console.
@Override
public void onCreate() {
super.onCreate();
// Set the Account ID, AccessKey ID, and AccessKey Secret for SDK access.
DNSResolver.Init(this, accountId, accessKeyId, accessKeySecret);
// Sets domain names for cache keep-alive. The resolution of a configured domain name is automatically initiated at 75% of its TTL to ensure that resolution requests for the domain name always hit the cache.
DNSResolver.setKeepAliveDomains(new String[]{"your-domain-1","your-domain-2",...});
// Pre-loads specified domains to IPv4 addresses. Replace the placeholder domains with the ones that you want to resolve.
DNSResolver.getInstance().preLoadDomains(DNSResolver.QTYPE_IPV4,new String[]{"your-domain-to-preload-1","your-domain-to-preload-2",...});
}
}
En iyi uygulamalar
En yüksek performansı elde etmek için ön çözümleme özelliğini süresi dolmuş yanıtları önbelleğe alma ile birlikte kullanın.
Ön çözümleme, uygulama başlatıldığında sonuçları önbelleğe alır. Süresi dolmuş yanıtlara izin verilmesi, TTL sona erdikten sonra bile önbellekteki IP adreslerinin anında döndürülmesini sağlayarak neredeyse sıfır gecikme süresiyle çözümleme yapılmasına olanak tanır.
Önceden yüklenen alan adları, sonraki isteklerde yerel önbellekten karşılanır ve ağ gidiş-dönüşleri ortadan kaldırılır.
1. Ön çözümleme
Uygulama başlatma sırasında önbelleği etkinleştirin ve önemli alan adlarını önceden çözümleyin.
Application sınıfının onCreate() yönteminde, alan adlarınızı önceden çözümleyip sonuçları yerel olarak önbelleğe alın.
1. Yalnızca IPv4 senaryoları
//********For IPv4-only scenarios*******
public class DnsCacheApplication extends Application{
private String accountId = "Your Account ID"; // Set your Account ID from the console.
private String accessKeyId = "Your AccessKey ID"; // Set your AccessKey ID from the console.
private String accessKeySecret = "Your AccessKey Secret"; // Set your AccessKey Secret from the console.
@Override
public void onCreate() {
super.onCreate();
// Set the Account ID, AccessKey ID, and AccessKey Secret for SDK access.
DNSResolver.Init(this, accountId, accessKeyId, accessKeySecret);
DNSResolver.setEnableCache(true); // Enable caching. Default value: true.
// The IPv4 record type for pre-resolution.
// Pre-loads specified domains to IPv4 addresses. Replace the placeholder domains with the ones that you want HTTPDNS to resolve.
DNSResolver.getInstance().preLoadDomains(DNSResolver.QTYPE_IPV4,new String[]{"your-domain-to-preload-1","your-domain-to-preload-2",...});
}
}
2. IPv6 desteği
//********For scenarios that require IPv6 support*******
public class DnsCacheApplication extends Application{
private String accountId = "Your Account ID"; // Set your Account ID from the console.
private String accessKeyId = "Your AccessKey ID"; // Set your AccessKey ID from the console.
private String accessKeySecret = "Your AccessKey Secret"; // Set your AccessKey Secret from the console.
@Override
public void onCreate() {
super.onCreate();
// Set the Account ID, AccessKey ID, and AccessKey Secret for SDK access.
DNSResolver.Init(this, accountId, accessKeyId, accessKeySecret);
DNSResolver.setEnableCache(true); // Enable caching. Default value: true.
DNSResolver.setEnableIPv6(true); // Specifies whether to resolve domain names over an IPv6 network. Default value: false.
DNSResolver.setEnableSpeedTest(true); // Specifies whether to enable IP speed testing. Default value: false.
// The IPv4 and IPv6 record types for pre-resolution.
// Pre-loads specified domains to IPv4 and IPv6 addresses. Replace the placeholder domains with the ones that you want HTTPDNS to resolve.
DNSResolver.getInstance().preLoadDomains(DNSResolver.QTYPE_IPV4_IPV6,new String[]{"your-domain-to-preload-1","your-domain-to-preload-2",...});
}
}
2. Süresi dolmuş yanıtlara izin verin
Ağ isteklerinden önce IP adreslerini önbellekten okuyun; süresi dolmuş girişlerin hemen döndürülmesine izin verin. Önbellek, arka planda eşzamansız olarak güncellenir.
1. Yalnızca IPv4 senaryoları
//********For IPv4-only scenarios*******
@Override
public List<InetAddress> lookup(@NonNull String hostname) throws UnknownHostException {
// Prioritize getting the IP address from the cache. The second parameter, if true, allows returning expired but usable records.
String[] IPArray = mDNSResolver.getIpv4ByHostFromCache(hostname,true);
if (IPArray == null || IPArray.length == 0){
// If the cache is not hit, initiate an asynchronous resolution.
IPArray = mDNSResolver.getIPsV4ByHost(hostname);
}
if (IPArray != null && IPArray.length > 0) {
List<InetAddress> inetAddresses = new ArrayList<>();
InetAddress address;
for (String ip : IPArray) {
address = InetAddress.getByName(ip);
inetAddresses.add(address);
}
if (!inetAddresses.isEmpty()) {
return inetAddresses;
}
}
return okhttp3.Dns.SYSTEM.lookup(hostname);
}
2. IPv6 desteği
//********For scenarios that require IPv6 support*******
@Override
public List<InetAddress> lookup(@NonNull String hostname) throws UnknownHostException {
// Prioritize getting the IP address from the cache. The second parameter, if true, allows returning expired but usable records.
String[] IPArray = mDNSResolver.getIpsByHostFromCache(hostname,true);
if (IPArray == null || IPArray.length == 0){
// If the cache is not hit, initiate an asynchronous resolution.
IPArray = mDNSResolver.getIpsByHost(hostname);
}
if (IPArray != null && IPArray.length > 0) {
List<InetAddress> inetAddresses = new ArrayList<>();
InetAddress address;
for (String ip : IPArray) {
address = InetAddress.getByName(ip);
inetAddresses.add(address);
}
if (!inetAddresses.isEmpty()) {
return inetAddresses;
}
}
return okhttp3.Dns.SYSTEM.lookup(hostname);
}
Kullanım notları
HTTPDNS üzerinden aldığınız bir IP adresini kullanarak istek gönderirken, HTTP
Hostüstbilgisini orijinal alan adına ayarlayın.-
HTTPDNS SDK'sı boş bir IP döndürürse, orijinal alan adı URL'sine geri dönün:
String ip = DNSResolver.getInstance().getIPV4ByHost("your-domain"); if (ip != null) { // Replace the host in the URL with the IP address to make an API request. }else { // Use the request URL of the original domain name to make a fallback request. // In this case, use the original URL that contains the domain name to make a network request. } Demo programını indirin ve HTTPDNS SDK entegrasyonu için referans olarak kullanın.
Entegrasyon sonrasında, konsoldaki Trafik Analizi sayfasında işlemin başarılı olduğunu doğrulayın. Trafik görünmüyorsa Account ID, AccessKey ID ve AccessKey Secret değerlerinin doğru şekilde girildiğini kontrol edin.
Yerinde DNS
v2.3.0 sürümünden itibaren HTTPDNS Android SDK, yerinde DNS dağıtımı desteği sunar.
Yerinde DNS; veri uyumluluğu ve özel çözümleme ilkeleri gerektiren senaryolar (finans, kamu, büyük ölçekli işletmeler) için uygundur. SDK dört dağıtım modunu destekler: yalnızca genel cloud, yalnızca yerinde ve iki ana-yedek hibrit yapı.
Temel yetenekler
Yerinde dağıtım desteği: IPv4/IPv6 adresleri veya ana bilgisayar alan adları kullanılarak yerinde DNS hizmet uç noktalarının yapılandırılmasını destekler.
Çift yönlü kimlik doğrulama: Bu mekanizma, istekleri müşteriye özgü
accessKeyIdveaccessKeySecretile imzalayarak güvenli iletişimi sağlar.Devre kesme ve sağlık denetimleri: Bir yerinde DNS düğümü art arda 3 veya daha fazla kez başarısız olursa devre kesme otomatik olarak tetiklenir. Ardından, belirtilen
healthCheckDomainkullanılarak düğümün kullanılabilirliği her dakika kontrol edilir. Düğüm kurtarma sağladığında otomatik olarak yeniden etkinleştirilir.Sertifika doğrulama denetimi: 2.3.1.beta sürümünden başlayarak, yerinde DNS testleri için TLS sertifika doğrulamasını devre dışı bırakabilirsiniz. Beta sürümleri yalnızca test amaçlıdır ve üretim ortamlarında kullanılmamalıdır. Android SDK sürüm notu
Akıllı geri dönüş: Birincil DNS (genel cloud DNS veya yerinde DNS) bir alan adını çözümleyemez ve hata sayısı belirtilen eşiğe ulaşırsa, sistem çözümlemenin yüksek kullanılabilirliğini sağlamak için otomatik olarak yedek DNS'ye geçer.
Sorunsuz API uyumluluğu: Genel cloud DNS veya yerinde DNS kullanıyor olun, çözümleme API'sini çağırma yöntemi aynı kalır. İş mantığınızı değiştirmenize gerek yoktur.
Yapılandırma
1. Yalnızca genel cloud DNS
Bu mod, yerinde DNS dağıtmamış standart SaaS kullanıcıları için tasarlanmıştır.
DNSResolver.Init(this, accountID, accessKeyId, accessKeySecret);
2. Yalnızca yerinde DNS
Bu mod, tamamen kendi yerinde DNS altyapısına güvenen müşteriler için uygundur.
DNSResolver.InitFusionDNS(this,new String[]{"1.1.X.X","2.2.X.X"},null,null,"443", "check.example.com", "your_fusion_ak", "your_fusion_sk");
// Optional: Disable certificate validation (for test environments only, requires a beta SDK version, e.g., 2.3.1.beta).
// DNSResolver.setEnableCertificateValidation(false);
3. Birincil: Genel bulut, yedek: Yerinde
Birincil Alibaba Cloud genel HTTPDNS bir alan adını çözümleyemediğinde sistem otomatik olarak yerinde DNS'e yük devreder.
// Primary: public cloud DNS
DNSResolver.Init(this, accountID, accessKeyId, accessKeySecret);
// Standby: on-premises DNS
DNSResolver.InitFusionDNS(this,new String[]{"1.1.X.X","2.2.X.X"},null,null,"443", "check.example.com", "your_fusion_ak", "your_fusion_sk");
// Optional: Disable certificate validation (for test environments only, requires a beta SDK version, e.g., 2.3.1.beta).
// DNSResolver.setEnableCertificateValidation(false);
4. Birincil: Yerinde, yedek: Genel bulut
Yerinde DNS'i birincil DNS olarak kullanın. Yerinde DNS bir alan adını çözümleyemediğinde sistem otomatik olarak Alibaba Cloud genel bulut DNS'ine yük devreder.
// Primary: on-premises DNS
DNSResolver.InitFusionDNS(this,new String[]{"1.1.X.X","2.2.X.X"},null,null,"443", "check.example.com", "your_fusion_ak", "your_fusion_sk");
// Optional: Disable certificate validation (for test environments only, requires a beta SDK version, e.g., 2.3.1.beta).
// DNSResolver.setEnableCertificateValidation(false);
// Standby: public cloud DNS
DNSResolver.Init(this, accountID, accessKeyId, accessKeySecret);
Yeni API'ler
SDK, yerinde dağıtım ve yüksek kullanılabilirlik olağanüstü durum kurtarma için üç temel API ekler:
1. Uç noktaları ve kimlik doğrulamayı yapılandırma
/** For on-premises DNS used in on-premises deployments. You do not need to call this method if you use only public DNS.
*
* Sets the address and authentication information for the on-premises DNS server.
* Customers use this interface to pass the address and authentication credentials of the private DNS server.
* The SDK uses this information to initiate requests.
* @param ctx The context.
* @param serverIpv4Arr The array of IPv4 addresses (can be nil).
* @param serverIpv6Arr The array of IPv6 addresses (can be nil).
* @param serverHostArr The array of host domain names (can be nil).
* @param port The service port, such as "443". If nil, the default port "443" is used.
* @param healthCheckDomain The domain name that is used for health checks after circuit breaking is triggered. When a resolution service consecutively fails more than three times, circuit breaking is triggered, and the IP address of that service enters the healthCheck state. Subsequent requests will not be sent to this service.
* A timer runs every minute to call the resolution API by using this healthCheckDomain to probe whether the resolution service is available. If the probe is successful, the service returns to the alive state, and subsequent requests can be sent to this service.
* @param accessKeyId The customer's private accessKeyId, which is used for authentication.
* @param accessKeySecret The customer's private accessKeySecret, which is used for authentication.
*/
public static void InitFusionDNS(Context ctx,String[] serverIpv4Arr, String[] serverIpv6Arr, String[] serverHostArr, String port, String healthCheckDomain, String accessKeyId, String accessKeySecret)
2. TLS sertifika doğrulamasını kontrol etme
Yerinde DNS için TLS sertifika doğrulamasını kontrol edin. Android SDK'nın beta derlemeleri 2.3.1 sürümünden itibaren yayımlanır ve 2.3.1 ile eşleşen beta derlemenin adı 2.3.1.beta'dır. Beta derleme, testleri çalıştırabilmeniz için yerinde DNS'ye yönelik TLS sertifika doğrulamasını devre dışı bırakmanıza olanak tanır. Beta derlemeler yalnızca test kolaylığı sağlamak amacıyla bulunur. Bir beta derlemeyi üretim ortamında asla kullanmayın.
/** For on-premises DNS used in on-premises deployments. You do not need to call this method if you use only public DNS.
*
* Specifies whether to enable certificate validation for on-premises DNS. Default value: true. If the server is not configured with a domain certificate or an IP certificate, you can set this parameter to false for testing. In production environments, we strongly recommend that you set this parameter to true. Otherwise, security risks may arise.
* @param enable Set this parameter to true to enable certificate validation (default), or false to disable it.
*/
public static void setEnableCertificateValidation(boolean enable)
3. Geri dönüş eşik değerini ayarlayın
/** If you configure both public cloud DNS and on-premises DNS, you can specify the number of times that DNS resolution on the primary DNS must fail before the system automatically falls back to the standby DNS. If you configure only one type of DNS, you do not need to call this method.
*
* Specifies the number of times that DNS resolution on the primary DNS must fail before the system automatically falls back to the standby DNS. If you configure only one type of DNS, you do not need to call this method.
* @param fallbackThreshold The failure threshold. Default: 4 if the primary DNS is public cloud DNS, or 2 if the primary DNS is on-premises DNS.
* Valid range: [0, 4]. A value of 0 indicates an immediate fallback.
*/
public static void setFallbackThreshold(int fallbackThreshold)