Yerleşik önbelleğe sahip güvenilir alan adı çözümlemesi için HTTPDNS iOS SDK'sını uygulamanıza entegre edin.
Genel bakış
iOS SDK, DoH JSON API işlevini kapsülleyerek HTTPDNS üzerinden iOS uygulamalarında alan adı çözümlemesi için API'ler ve Yaşam Süresi (TTL) ile En Son Kullanılan (LRU) ilkelerine dayalı verimli alan adı önbellekleme sağlar. Alan adı çözümleme anormalliklerini gidermek ve hassas, düşük maliyetli çözümleme zamanlaması elde etmek için HTTPDNS hizmetini iOS uygulamanıza entegre edin.
iOS 14 yerel şifreli DNS çözümü kullanarak HTTPDNS hizmetini varsayılan şifreli DNS çözücüsü olarak da ayarlayabilirsiniz.
Temel avantajlar:
-
Kullanımı kolay:
HTTPDNS hizmetini uygulamanıza entegre etmek için minimum kod yazmanız yeterlidir.
-
Sıfır gecikme:
Dahili bir LRU önbelleği, çözülen IP adreslerini yerel olarak depolar ve süresi dolmuş girdileri proaktif olarak yeniler; bu sayede sıfır gecikmeli çözümleme mümkün olur.
Objective-C örnek projesi: alidns_ios_demo örnek proje kaynak kodu.
Swift örnek projesi: DNSResolverSwiftDemo örnek proje kaynak kodu.
SDK entegrasyonu
SDK'yı içe aktarma
CocoaPods
-
Podfile dosyanızda depo konumunu belirtin. Ana deponun dahil edildiğinden emin olun.
source 'https://github.com/CocoaPods/Specs.git' source 'https://github.com/aliyun/aliyun-specs.git' -
Proje hedefiniz için bağımlılığı ekleyin:
pod 'AlicloudPDNS'
Manuel
iOS SDK'yı SDK İndirme sayfasından indirin.
SDK çerçevesi
pdns-sdk-ios.frameworkedindikten sonra bunu projenize manuel olarak ekleyin.-
Gerekli sistem kitaplıklarını içe aktarın:
Foundation.framework
SystemConfiguration.framework
CoreFoundation.framework
CoreTelephony.framework
Projenizin Build Settings bölümünde Other Linker Flags seçeneğine -ObjC işaretini ekleyin.
SDK başlatma
Başlatmadan önce hesabınızı konsolda kaydederek Hesap Kimliğini ve AccessKey kimlik bilgilerini alın.
Çözümleme hatalarını önlemek için SDK'yı uygulamanızın yaşam döngüsünde mümkün olan en erken aşamada başlatın.
SDK'yı application:didFinishLaunchingWithOptions: yönteminde başlatın.
DNSResolver *resolver = [DNSResolver share];
// setAccountId:@"******": Replace the asterisks with the Account ID from the Access Configuration page in the console.
// andAccessKeyId:@"********": Replace the asterisks with the AccessKey ID of the key that you created on the Access Configuration page.
// andAccesskeySecret:@"********": Replace the asterisks with the AccessKey Secret of the key that you created on the Access Configuration page.
[resolver setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
// Specify domains for automatic cache updates. The array can contain a maximum of 10 domains.
[resolver setKeepAliveDomains:@[@"your_domain_1", @"your_domain_2"]];
// Pre-resolve domains that you expect to use later.
[resolver preloadDomains:@[@"domain1", @"domain2", @"domain3"] complete:^{
// All domains are pre-resolved.
}];
API referansı
Ortak ayarlar
1. Hesap Kimliği ve kimlik doğrulama
Zorunludur. Uygulamanızı kaydettiğinizde konsol benzersiz bir Hesap Kimliği oluşturur. Kimlik doğrulama için bir AccessKey oluşturmak üzere bir AccessKey çifti oluşturun ve ardından aşağıdaki şekilde yapılandırın:
// setAccountId:@"******": Replace the asterisks with the Account ID from the Access Configuration page in the console.
// andAccessKeyId:@"********": Replace the asterisks with the AccessKey ID of the key that you created on the Access Configuration page.
// andAccesskeySecret:@"********": Replace the asterisks with the AccessKey Secret of the key that you created on the Access Configuration page.
[[DNSResolver share] setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
Hesap Kimliğinizin, AccessKey ID'nizin veya AccessKey Secret'ınızın çalışan uygulamanız tarafından oluşturulan günlüklerde veya diğer verilerde açığa çıkmasını önlemek için üretim sürümünüzde SDK hata ayıklama günlüğünü devre dışı bırakın.
Örnek kod, Hesap Kimliği, AccessKey ID ve AccessKey Secret değerlerini doğrudan geçirir; bu kimlik bilgileri faturalama amacıyla kullanılır. Bu bilgilerin kötü amaçlı tersine mühendislik yoluyla açığa çıkmasını önlemek için üretim uygulamanızda düz metin kimlik bilgilerini sabit kodlamayın. Bunun yerine bunları kodlayın veya şifreleyin ve yalnızca gerektiğinde kodunu çözün veya şifresini çözün. Ayrıca uygulamanızın kodunu karıştırmanızı ve sağlamlaştırmanızı öneririz. Aksi takdirde Hesap Kimliğiniz, AccessKey ID'niz ve AccessKey Secret'ınız tehlikeye girebilir.
2. Çözümleme protokolünü ayarlama
scheme özelliğini kullanarak çözümleme protokolünü (HTTP veya HTTPS) ayarlayın.
SDK, daha iyi güvenlik sağladığı için varsayılan olarak HTTPS protokolünü kullanır ve önerir. HTTPDNS hizmeti, çözümleme isteği sayısına göre ücretlendirilir. HTTPS istekleri, HTTP isteklerinin beş katı oranında ücretlendirilir. İş ihtiyaçlarınıza göre bir şema türü seçin. Özelliği aşağıdaki gibi ayarlayın:
[DNSResolver share].scheme = DNSResolverSchemeHttps;
3. Önbelleği etkinleştirme veya devre dışı bırakma
Etkinleştirildiğinde, çözülen sonuçlar yerel olarak önbelleğe alınır; böylece sonraki aramalar önbellekten anında döndürülür.
Önbellekleme varsayılan olarak etkindir. Devre dışı bırakmak için aşağıdaki kodu kullanın:
[DNSResolver share].cacheEnable=NO;
4. Alan adları için keep-alive önbelleğini ayarlama
Etkinleştirildiğinde SDK, belirtilen alan adlarının önbellek girdilerinin süresi dolmadan önce proaktif olarak yenilenmesini sağlar. Bu işlem verileri güncel tutar ancak çözümleme isteklerini ve ağ trafiğini artırır. Bu özellik olmadan önbellek güncellemeleri yalnızca bir çözümleme yöntemi çağrıldığında gerçekleşir.
// The array can contain a maximum of 10 domains.
[[DNSResolver share] setKeepAliveDomains:@[@"www.taobao.com",@"www.aliyun.com"]];
-
Avantajlar:
Kayıtlar TTL süresi dolmadan önce hızlı bir şekilde güncellenir.
Ön çözümleme ile birlikte kullanıldığında ilk çözümleme gecikmesini 0 ms'ye indirebilir.
Dezavantaj: Bir kaydın TTL süresinin %75'inde yeniden istek göndermek ek maliyetlere neden olur.
5. Ön çözümleme
Uygulama başlangıcında alan adlarını önceden çözümleyerek sonraki aramaların neredeyse sıfır gecikmeyle önbellekten yanıt vermesini sağlayın.
Kod örneği:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
DNSResolver *resolver = [DNSResolver share];
// setAccountId:@"******": Replace the asterisks with the Account ID from the Access Configuration page in the console.
// andAccessKeyId:@"********": Replace the asterisks with the AccessKey ID of the key that you created on the Access Configuration page.
// andAccesskeySecret:@"********": Replace the asterisks with the AccessKey Secret of the key that you created on the Access Configuration page.
[resolver setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
resolver.cacheEnable = YES;
// Pre-resolve domains that you expect to use later.
[resolver preloadDomains:@[@"domain1", @"domain2", @"domain3"] complete:^{
// All domains are pre-resolved.
}];
return YES;
}
Gelişmiş ayarlar
1. Sunucu tarafı IPv6 erişimini etkinleştirme
HTTPDNS hizmeti çift yığın (IPv4 ve IPv6) erişimini destekler. SDK varsayılan olarak IPv4 kullanır.
IPv6 kullanmak için ağınızın bunu desteklediğinden emin olun ve özelliği etkinleştirin:
[DNSResolver share].ipv6Enable = YES;
2. Kısa mod
HTTPDNS DoH JSON API'si tam JSON veya basitleştirilmiş bir IP dizisi döndürür. SDK varsayılan olarak tam JSON kullanır.
Basitleştirilmiş IP dizisi biçimini kullanmak için:
[DNSResolver share].shortEnable = YES;
3. Önbellek boyutunu ayarlama
Önbellekleme etkinse önbelleğe alınacak alan adı sayısını özelleştirebilirsiniz. Desteklenen aralık 100 ila 500 arasındadır.
Varsayılan önbellek boyutu 100 alan adıdır. Özel bir önbellek boyutu ayarlamak için cacheCountLimit özelliğini kullanın:
[DNSResolver share].cacheCountLimit = 200;
4. IP hız testini etkinleştirme veya devre dışı bırakma
IP hız testi etkinleştirildiğinde çözümleme sonuçları gecikme süresine göre sıralanır ve en hızlı IP adresi ilk olarak döndürülür.
SDK v2.3.1 ve sonraki sürümlerde IP hız testi varsayılan olarak etkindir (YES). Daha önceki sürümlerde varsayılan olarak devre dışıdır (NO). Bu özelliği açıkça ayarlamak için aşağıdaki kodu kullanın:
[DNSResolver share].speedTestEnable=YES;
5. IP hız testi yöntemini ayarlama
Sondalama yöntemini yapılandırın: ICMP sondalaması için 0 olarak ayarlayın veya o bağlantı noktasındaki soket sondalaması için bir bağlantı noktası numarası (80, 443 vb.) belirtin.
SDK v2.3.1 ve sonraki sürümlerde varsayılan bağlantı noktası 80'dir. Daha önceki sürümlerde varsayılan bağlantı noktası 443'tür.
[DNSResolver share].speedPort = 80;
6. IPv6 hız testi handikapını ayarlama (v2.3.1 ve sonraki sürümlerde desteklenir)
Milisaniye cinsinden bir IPv6 hız testi handikapı ayarlayın. Bir çözümleme sonucu hem IPv4 hem de IPv6 adresleri içerdiğinde SDK, ölçülen IPv6 gecikmesinden bu handikapı düşer ve ardından gecikmeyi IPv4 gecikmesiyle karşılaştırır. Aralık handikap içinde kaldığı sürece IPv6 adresi yalnızca marjinal olarak daha yavaş olsa bile tercih edilir. Geçerli aralık 0 ila 1000 arasındadır. Bu ayar yalnızca IP hız testi etkin olduğunda etkili olur.
Varsayılan değer 0'dır ve handikapı devre dışı bırakır. Özel bir handikap ayarlamak için aşağıdaki kodu kullanın:
[DNSResolver share].speedTestIpv6PreferMs = 0;
7. ISS'ye özel alan adı önbelleğini etkinleştirme veya devre dışı bırakma
Etkinleştirildiğinde önbellek girdileri ISS ağı başına izole edilir. Devre dışı bırakıldığında tüm ağlar tek bir önbelleği paylaşır.
ISS'ye özel alan adı önbelleği varsayılan olarak etkindir.
[DNSResolver share].ispEnable = YES;
8. Negatif önbellek için maksimum TTL ayarlama
Başarısız aramaların sonuçlarını depolayan negatif önbellek için maksimum bir TTL ayarlayın.
Varsayılan değer 30 saniyedir. Negatif önbellek için özel bir maksimum TTL ayarlamak için aşağıdaki kodu kullanın:
[DNSResolver share].maxNegativeCache = 30;
9. Maksimum önbellek TTL'sini ayarlama
Sunucu tarafından sağlanan TTL değerlerinden bağımsız olarak girdi ömrünü sınırlamak için maksimum bir önbellek TTL'si ayarlayın.
Varsayılan değer 3600 saniyedir. Özel bir maksimum önbellek TTL'si ayarlamak için aşağıdaki kodu kullanın:
[DNSResolver share].maxCacheTTL= 3600;
10. Değişmez önbelleği etkinleştirme
[DNSResolver share].immutableCacheEnable = NO;// Immutable cache is disabled by default.
SDK üç önbellek güncelleme mekanizması sağlar:
-
Değişmez önbellek: Bu özellik etkinleştirildiğinde önbellek, uygulamanın çalışma süresi boyunca her zaman geçerli kabul edilir. SDK, sona erme kontrollerini ve güncellemelerini atlayarak çözümleme isteği sayısını en aza indirir.
Etkinleştirmek için şu komutu çağırın:
[DNSResolver share].immutableCacheEnable = YES -
Aktif önbellek güncellemesi: Önbelleğe alınmış çözümleme sonuçlarını güncel tutar. Bir alan adının yetkili kaydı değiştiğinde istekler düşük gecikmeli önbellek isabetlerinden yararlanmaya devam ederken SDK önbelleğe alınmış kayıtları yeniler. Dizi en fazla 10 alan adı ile sınırlıdır.
Etkinleştirmek için şu komutu çağırın:
[[DNSResolver share] setKeepAliveDomains:@[@"your_domain_1",@"your_domain_2"]] -
Pasif önbellek güncellemesi: Çözümleme sonuçlarını almak için aşağıdaki iki yöntemden birini çağırdığınızda önbellek pasif olarak güncellenir:
- (void)getIpv4DataWithDomain:(NSString *)domain complete:(void(^)(NSArray<NSString *> *dataArray))completeyöntemi, bir alan adı için IPv4 adreslerinden oluşan bir dizi alır. Önbellek boş değilse ve girdi TTL süresi içindeyse yöntem önbellekteki sonucu hemen döndürür. Aksi takdirde en son sonucu ağ üzerinden getirir, döndürür ve önbelleği günceller. Yüksek doğruluk gerektiren senaryolarda bu yöntemi kullanın.-
- (NSArray<NSString *> *)getIpv4ByCacheWithDomain:(NSString *)domain andExpiredIPEnabled:(BOOL)enableyöntemi, IPv4 çözümleme sonuçlarını önbellekten alır. Bu yöntemin davranışıenableparametresine bağlıdır.Parametre açıklaması:
enabledeğeriYESise yöntem, önbelleğin süresi dolmuş olsa bile (veya önbellek boşsanildöndürür) eski bir kaydı döndürür ve ardından önbelleği eşzamansız olarak günceller.NOise önbelleğin süresi dolduğunda veya boş olduğundanildöndürür ve ardından önbelleği eşzamansız olarak günceller.
11. Zaman aşımı
timeout özelliği, çözümleme için istek timeout değerini ayarlar. Varsayılan: 3 sn. Önerilen aralık: 2 sn ila 5 sn.
12. Eşzamanlı çözümleme isteği sayısının maksimum değerini ayarlama (v2.3.1 ve sonraki sürümlerde desteklenir)
SDK'nın gönderdiği eşzamanlı DNS çözümleme isteği sayısının maksimum değerini ayarlayın. Geçerli aralık 1 ila 50 arasındadır. Varsayılan değer 10'dur. Özel bir sınır ayarlamak için aşağıdaki kodu kullanın:
[DNSResolver share].maxConcurrentResolveCount = 10;
Hizmet API'leri
Kod örneği:
/// Pre-resolves domain information. Call this method at app startup. The results are stored in the cache to accelerate subsequent resolutions.
/// Automatically detects the network environment (IPv4-only, IPv6-only, or dual-stack) to get an IP suitable for the current network.
/// @param domainArray An array of domain names.
/// @param complete A callback that is executed after resolution is complete.
- (void)preloadDomains:(NSArray<NSString *> *)domainArray complete:(void(^)(void))complete;
/// Gets an array of IP addresses for a domain. This method automatically detects the network environment (IPv4-only, IPv6-only, or dual-stack) to get a suitable IP.
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IP over the network. If caching is disabled, it always fetches the IP over the network.
/// @param domain The domain name.
/// @param complete A callback that returns all IP addresses.
- (void)getIpsDataWithDomain:(NSString *)domain complete:(void(^)(NSArray<NSString *> *dataArray))complete;
/// Gets an array of IP addresses directly from the cache without waiting. This method automatically detects the network environment (IPv4-only, IPv6-only, or dual-stack).
/// Returns nil if the cache is empty. If the cache is not empty and `enable` is set to YES, it returns the cached data. If the data is expired, it asynchronously updates the cache. If the cache is not empty and `enable` is set to NO, it returns nil for expired entries and asynchronously updates the cache.
/// @param domain The domain name.
/// @param enable Specifies whether to return expired IP addresses.
- (NSArray<NSString *> *)getIpsByCacheWithDomain:(NSString *)domain andExpiredIPEnabled:(BOOL)enable;
/// Gets an array of IPv4 information objects for a domain.
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IPs over the network. If caching is disabled, it always fetches the IPs over the network.
/// @param domain The domain name.
/// @param complete A callback that returns all domain information objects.
- (void)getIpv4InfoWithDomain:(NSString *)domain complete:(void(^)(NSArray<DNSDomainInfo *> *domainInfoArray))complete;
/// Gets an array of IPv6 information objects for a domain.
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IPs over the network. If caching is disabled, it always fetches the IPs over the network.
/// @param domain The domain name.
/// @param complete A callback that returns all domain information objects.
- (void)getIpv6InfoWithDomain:(NSString *)domain complete:(void(^)(NSArray<DNSDomainInfo *> *domainInfoArray))complete;
/// Gets a random IPv4 information object for a domain.
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IP over the network. If caching is disabled, it always fetches the IP over the network.
/// @param domain The domain name.
/// @param complete A callback that returns one random domain information object.
- (void)getRandomIpv4InfoWithDomain:(NSString *)domain complete:(void(^)(DNSDomainInfo *domainInfo))complete;
/// Gets a random IPv6 information object for a domain.
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IP over the network. If caching is disabled, it always fetches the IP over the network.
/// @param domain The domain name.
/// @param complete A callback that returns one random domain information object.
- (void)getRandomIpv6InfoWithDomain:(NSString *)domain complete:(void(^)(DNSDomainInfo *domainInfo))complete;
/// Gets an array of IPv4 addresses for a domain.
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IPs over the network. If caching is disabled, it always fetches the IPs over the network.
/// @param domain The domain name.
/// @param complete A callback that returns all IP addresses.
- (void)getIpv4DataWithDomain:(NSString *)domain complete:(void(^)(NSArray<NSString *> *dataArray))complete;
/// Gets an array of IPv6 addresses for a domain.
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IPs over the network. If caching is disabled, it always fetches the IPs over the network.
/// @param domain The domain name.
/// @param complete A callback that returns all IP addresses.
- (void)getIpv6DataWithDomain:(NSString *)domain complete:(void(^)(NSArray<NSString *> *dataArray))complete;
/// Gets a random IPv4 address for a domain.
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IP over the network. If caching is disabled, it always fetches the IP over the network.
/// @param domain The domain name.
/// @param complete A callback that returns one random IP address.
- (void)getRandomIpv4DataWithDomain:(NSString *)domain complete:(void(^)(NSString *data))complete;
/// Gets a random IPv6 address for a domain.
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IP over the network. If caching is disabled, it always fetches the IP over the network.
/// @param domain The domain name.
/// @param complete A callback that returns one random IP address.
- (void)getRandomIpv6DataWithDomain:(NSString *)domain complete:(void(^)(NSString *data))complete;
/// Pre-resolves IPv4 information for domains. Call this at app startup. The results are stored in the cache to accelerate subsequent resolutions.
/// @param domainArray An array of domain names.
/// @param complete A callback that is executed after resolution is complete.
- (void)preloadIpv4Domains:(NSArray<NSString *> *)domainArray complete:(void(^)(void))complete;
/// Pre-resolves IPv6 information for domains. Call this at app startup. The results are stored in the cache to accelerate subsequent resolutions.
/// @param domainArray An array of domain names.
/// @param complete A callback that is executed after resolution is complete.
- (void)preloadIpv6Domains:(NSArray<NSString *> *)domainArray complete:(void(^)(void))complete;
/// Gets an array of IPv4 addresses directly from the cache without waiting.
/// Returns nil if the cache is empty. If the cache is not empty and `enable` is set to YES, it returns the cached data. If the data is expired, it asynchronously updates the cache. If the cache is not empty and `enable` is set to NO, it returns nil for expired entries and asynchronously updates the cache.
/// @param domain The domain name.
/// @param enable Specifies whether to return expired IP addresses.
- (NSArray<NSString *> *)getIpv4ByCacheWithDomain:(NSString *)domain andExpiredIPEnabled:(BOOL)enable;
/// Gets an array of IPv6 addresses directly from the cache without waiting.
/// Returns nil if the cache is empty. If the cache is not empty and `enable` is set to YES, it returns the cached data. If the data is expired, it asynchronously updates the cache. If the cache is not empty and `enable` is set to NO, it returns nil for expired entries and asynchronously updates the cache.
/// @param domain The domain name.
/// @param enable Specifies whether to return expired IP addresses.
- (NSArray<NSString *> *)getIpv6ByCacheWithDomain:(NSString *)domain andExpiredIPEnabled:(BOOL)enable;
/// Collects request statistics.
-(NSArray *)getRequestReportInfo;
API kullanım örnekleri
1. Temel bilgileri ayarlama
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Initialization method
DNSResolver *resolver = [DNSResolver share];
// setAccountId:@"******": Replace the asterisks with the Account ID from the Access Configuration page in the console.
// andAccessKeyId:@"********": Replace the asterisks with the AccessKey ID of the key that you created on the Access Configuration page.
// andAccesskeySecret:@"********": Replace the asterisks with the AccessKey Secret of the key that you created on the Access Configuration page.
[resolver setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
// Specify domains for automatic cache updates. The array can contain a maximum of 10 domains.
[resolver setKeepAliveDomains:@[@"your_domain_1",@"your_domain_2"]];
// Pre-resolve domains to get resolution results in advance and store them in the cache.
[resolver preloadDomains:@[@"domain1", @"domain2", @"domain3"] complete:^{
// All domains are pre-resolved.
}];
return YES;
}
2. Alan adı çözümleme API'sini kullanma
SDK, DNSResolver.h dosyasında birden çok çözümleme yöntemi sağlar. Aşağıdaki örnek, ağ ortamına (yalnızca IPv4, yalnızca IPv6 veya çift yığın) otomatik olarak uyum sağlayan bir yöntemi kullanır.
API bildirimi:
/// Gets an array of IP addresses for a domain. This method automatically adapts to the network environment (IPv4-only, IPv6-only, or dual-stack).
/// If caching is enabled, it returns data from the cache first. If the cache is empty or expired, it fetches the IPs over the network. If caching is disabled, it always fetches the IPs over the network.
/// @param domain The domain name.
/// @param complete A callback that returns all IP addresses.
- (void)getIpsDataWithDomain:(NSString *)domain complete:(void(^)(NSArray<NSString *> *dataArray))complete;
API çağrı örneği:
[[DNSResolver share] getIpsDataWithDomain:@"www.taobao.com" complete:^(NSArray<NSString *> *dataArray) {
// dataArray is the array of IP addresses for www.taobao.com.
if (dataArray.count > 0) {
//TODO: Use an IP address for the URL connection.
}
}];
3. Çözümleme sonuçlarını doğrudan önbellekten alma
API bildirimi:
/// Gets an array of IP addresses directly from the cache without waiting. This method automatically adapts to the network environment (IPv4-only, IPv6-only, or dual-stack).
/// Returns nil if the cache is empty. If the cache is not empty and `enable` is set to YES, it returns the cached data. If the data is expired, it asynchronously updates the cache. If the cache is not empty and `enable` is set to NO, it returns nil for expired entries and asynchronously updates the cache.
/// @param domain The domain name.
/// @param enable Specifies whether to return expired IP addresses.
- (NSArray<NSString *> *)getIpsByCacheWithDomain:(NSString *)domain andExpiredIPEnabled:(BOOL)enable;
Çağrı örneği:
NSArray *result = [[DNSResolver share] getIpsByCacheWithDomain:@"your_domain" andExpiredIPEnabled:YES];
// Use the cached result.
if (result.count > 0) {
//TODO: Use an IP address for the URL connection.
}
Not: Sonuçları doğrudan önbellekten almak hızlıdır ancak önbellek boşsa veya önbelleğin süresi dolmuşsa ve enable değeri NO olarak ayarlanmışsa yöntem nil döndürür.
4. Önbelleği temizleme
API bildirimi:
/// `hostArray` is an array of hostnames to clear from the cache. To clear all data, pass nil or an empty array.
-(void)clearHostCache:(NSArray <NSString *>*)hostArray;
Çağrı örneği:
[[DNSResolver share] clearHostCache:@[@"domain1", @"domain2"]];
5. İstatistik toplama
API bildirimi:
/// Collects request statistics.
-(NSArray *)getRequestReportInfo;
Çağrı örneği:
NSArray *array = [[DNSResolver share] getRequestReportInfo];
Veri biçimi:
(
{
avgRtt = "1"; // Average domain resolution time (ms)
cacheDnsNum = 0; // Number of cache hits
domain = "www.taobao.com"; // The resolved domain
gobackLocaldnsNum = 0; // Number of fallbacks to local DNS
localErro = 0; // Number of local DNS resolution failures
maxRtt = "60"; // Maximum domain resolution time (ms)
noPermissionErro = 0; // Number of authentication failures
noResponseErro = 0; // Number of no-response errors
requestPDnsNum = 1; // Number of recursive queries
sp = "China Mobile"; // ISP name
successNum = 1; // Number of successful resolutions
timeoutErro = 0; // Number of network timeout errors
type = 28; // IP type: 1 for IPv4, 28 for IPv6
urlParameterErro = 0; // Number of URL parameter format errors
urlPathErro = 0; // Number of URL path errors
}
......
);
Alan adı çözümlemesi için en iyi uygulamalar
En iyi performans için ön çözümlemeyi stale-while-revalidate mekanizmasıyla birleştirin.
Anahtar alan adlarını başlangıçta önceden çözümlemek önbelleği doldurur; böylece sonraki aramalar ağ gidiş-dönüşlerinden kaçınarak neredeyse sıfır gecikmeli çözümleme sağlar.
Yerleşik önbellek daha sonra sonraki isteklere doğrudan bellekten hizmet verir.
1. Ön çözümleme
Önbelleği etkinleştirin ve uygulama başlangıcında anahtar alan adlarını önceden çözümleyin.
AppDelegate öğesinin application:didFinishLaunchingWithOptions: yönteminde uygulamanızda kullanılan alan adlarını önceden çözümleyin ve sonuçları yerel bellekte önbelleğe alın.
1. Yalnızca IPv4 senaryoları için
//******** For IPv4-only scenarios *******
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
DNSResolver *resolver = [DNSResolver share];
// setAccountId:@"******": Replace the asterisks with the Account ID from the Access Configuration page in the console.
// andAccessKeyId:@"********": Replace the asterisks with the AccessKey ID of the key that you created on the Access Configuration page.
// andAccesskeySecret:@"********": Replace the asterisks with the AccessKey Secret of the key that you created on the Access Configuration page.
[resolver setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
// Enable caching. Default is YES.
resolver.cacheEnable = YES;
// Pre-resolve IPv4 information for domains that you expect to use later.
[resolver preloadIpv4Domains:@[@"domain1", @"domain2", @"domain3"] complete:^{
// All domains are pre-resolved.
}];
return YES;
}
2. IPv6 senaryoları için
//******** For dual-stack scenarios that support IPv6 *******
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
DNSResolver *resolver = [DNSResolver share];
// setAccountId:@"******": Replace the asterisks with the Account ID from the Access Configuration page in the console.
// andAccessKeyId:@"********": Replace the asterisks with the AccessKey ID of the key that you created on the Access Configuration page.
// andAccesskeySecret:@"********": Replace the asterisks with the AccessKey Secret of the key that you created on the Access Configuration page.
[resolver setAccountId:@"******" andAccessKeyId:@"********" andAccesskeySecret:@"********"];
// Enable caching. Default is YES.
resolver.cacheEnable = YES;
// Enable domain resolution over IPv6 networks. Default is NO.
resolver.ipv6Enable = YES;
// Enable IP speed test. Default is NO.
resolver.speedTestEnable = YES;
// Pre-resolve domains. This automatically detects the network (IPv4-only, IPv6-only, or dual-stack) and gets a suitable IP.
[resolver preloadDomains:@[@"domain1", @"domain2", @"domain3"] complete:^{
// All domains are pre-resolved.
}];
return YES;
}
2. Eski yanıtlara izin verme
Bir ağ isteği yapmadan önce önbellekten IP adresini alın ve süresi dolmuş kayıtlara izin verin (andExpiredIPEnabled:YES). TTL süresi dolmuş olsa bile önbellek dolu olduğu sürece bu işlem anında bir sonuç döndürerek sıfır gecikmeli çözümleme sağlar.
1. Yalnızca IPv4 senaryoları için
//******** For IPv4-only scenarios *******
__weak typeof(self) ws = self;
// Prioritize getting the IP from the cache, allowing stale but usable records.
NSArray<NSString *> *cachedIPs = [[DNSResolver share] getIpv4ByCacheWithDomain:domain andExpiredIPEnabled:YES];
if (cachedIPs && cachedIPs.count > 0) {
NSString *ip = cachedIPs.firstObject;
NSLog(@"Fast cache hit. Domain %@ resolved to IP: %@", domain, ip);
[self requestWithIP:ip domain:domain]; // Connect directly using the IP.
} else {
// Cache miss. Perform an asynchronous resolution.
[[DNSResolver share] getIpv4DataWithDomain:domain complete:^(NSArray<NSString *> *resolvedIPs) {
if (resolvedIPs && resolvedIPs.count > 0) {
NSString *ip = resolvedIPs.firstObject;
NSLog(@"Async resolution complete. Domain %@ resolved to IP: %@", domain, ip);
[ws requestWithIP:ip domain:domain]; // Connect directly using the IP.
} else {
NSLog(@"Domain resolution failed. Falling back to original domain.");
[ws requestWithIP:domain domain:domain]; // Fallback: Use the original domain.
}
}];
}
2. IPv6 senaryoları için
//******** For dual-stack scenarios that support IPv6 *******
__weak typeof(self) ws = self;
// Prioritize getting the IP from the cache, allowing stale but usable records.
NSArray<NSString *> *cachedIPs = [[DNSResolver share] getIpsByCacheWithDomain:domain andExpiredIPEnabled:YES];
if (cachedIPs && cachedIPs.count > 0) {
NSString *ip = cachedIPs.firstObject;
NSLog(@"Fast cache hit. Domain %@ resolved to IP: %@", domain, ip);
[self requestWithIP:ip domain:domain]; // Connect directly using the IP.
} else {
// Cache miss. Perform an asynchronous resolution.
[[DNSResolver share] getIpsDataWithDomain:domain complete:^(NSArray<NSString *> *resolvedIPs) {
if (resolvedIPs && resolvedIPs.count > 0) {
NSString *ip = resolvedIPs.firstObject;
NSLog(@"Async resolution complete. Domain %@ resolved to IP: %@", domain, ip);
[ws requestWithIP:ip domain:domain]; // Connect directly using the IP.
} else {
NSLog(@"Domain resolution failed. Falling back to original domain.");
[ws requestWithIP:domain domain:domain]; // Fallback: Use the original domain.
}
}];
}
Kullanım notları
pdns-sdk-ios.frameworken az iOS 9.0 sürümü gerektirir.HTTP üzerinden istek yaptığınızda
Info.plistdosyanızdaApp Transport Security Settings->Allow Arbitrary LoadsdeğeriniYESolarak ayarlamalısınız.-
HTTPDNS üzerinden bir IP adresi çözdükten sonra hizmet istekleri yaparken
HostHTTP üst bilgisini orijinal alan adına ayarlayın.Örnek:
// `ip` is the IP address resolved from the original domain name. NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@", ip]]; NSMutableURLRequest *mutableReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval: 10]; // Set the host. [mutableReq setValue:@"original_domain" forHTTPHeaderField:@"host"]; -
Bir geri dönüş mekanizması uygulayın: SDK herhangi bir IP adresi döndürmezse isteği orijinal alan adını kullanarak yapın.
NSArray *array = [[DNSResolver share] getIpsByCacheWithDomain:@"original_domain" andExpiredIPEnabled:YES]; if (array && array.count > 0 && array.firstObject.length > 0) { // Replace the host in the URL with the IP and make the request. } else { // Implement fallback logic (use the original URL for the request). } Bir HTTP proxy'si mevcut olduğunda ve IP tabanlı bir URL ile HTTPDNS kullandığınızda proxy, orijinal ana bilgisayar adı yerine IP adresini Host bilgisi olarak iletir. Bu durum hedef sunucunun isteği doğru şekilde işlemesini engeller. Cihazda proxy'nin etkin olup olmadığını kontrol edin. Cihazınız proxy modundaysa alan adı çözümlemesi için HTTPDNS kullanmayın.
Yerinde DNS
v2.3.0 ve sonraki sürümlerden itibaren HTTPDNS iOS SDK'sı özel dağıtımlar için yerinde DNS'i destekler.
Yerinde DNS; finans, devlet veya büyük kuruluşlar gibi sıkı veri uyumluluğu ve özel çözümleme ilkeleri gerektiren senaryolar için uygundur. SDK dört dağıtım modunu destekler: yalnızca genel cloud, yalnızca yerinde DNS ve genel cloud ile yerinde DNS'in karşılıklı yedek olarak hizmet verdiği iki birincil/yedek hibrit mod.
Temel özellikler
Özel dağıtım desteği: Yerinde DNS sunucusu uç noktalarını IPv4/IPv6 adresleri veya ana bilgisayar adları kullanarak yapılandırın.
Karşılıklı kimlik doğrulama: İsteklerinizi imzalamak ve iletişimi güvence altına almak için özel
accessKeyIdveaccessKeySecretdeğerlerinizi kullanın.Devre kesme ve sağlık kontrolleri: Bir yerinde DNS düğümü üç veya daha fazla ardışık kez başarısız olursa devre kesme otomatik olarak tetiklenir. Ardından sistem, belirtilen
healthCheckDomaindeğerini kullanarak her dakika kullanılabilirliği kontrol eder. Düğüm kurtardıktan sonra otomatik olarak yeniden etkinleştirilir.Sertifika doğrulama denetimi: TLS sertifika doğrulamasını etkinleştirin veya devre dışı bırakın. Üretim ortamlarında bunu etkinleştirmenizi kesinlikle öneririz.
Akıllı yük devretme: Birincil DNS (genel cloud veya yerinde) bir hata eşiğine ulaştığında otomatik olarak yedek DNS'e yük devreder ve çözümleme için yüksek kullanılabilirlik sağlar.
Sorunsuz API uyumluluğu: Genel cloud DNS veya yerinde DNS kullanıyor olmanızdan bağımsız olarak çözümleme API çağrıları aynı kalır ve iş mantığınızda değişiklik yapılmasını gerektirmez.
Yapılandırma örnekleri
1. Yalnızca genel cloud DNS kullanma
Bu mod, yerinde DNS dağıtmamış standart SaaS kullanıcıları içindir.
DNSResolver *resolver = [DNSResolver share];
[resolver setAccountId:@"******"
andAccessKeyId:@"********"
andAccesskeySecret:@"********"];
2. Yalnızca yerinde DNS kullanma (özel dağıtım)
Bu mod, tamamen kendi yerinde DNS'lerine güvenen müşteriler içindir.
DNSResolver *resolver = [DNSResolver share];
[resolver setFusionDNSWithIPv4:@[@"1.1.X.X", @"2.2.X.X"]
IPv6:nil
Host:nil
Port:@"443"
HealthCheckDomain:@"check.example.com"
accessKeyId:@"your_fusion_ak"
accesskeySecret:@"your_fusion_sk"];
// Optional: Disable certificate validation (for test environments only).
// [resolver setEnableCertificateValidation:NO];
3. Genel cloud birincil, yerinde yedek
Birincil Alibaba Cloud genel HTTPDNS başarısız olursa çözümleme otomatik olarak yerinde DNS'e yük devreder.
DNSResolver *resolver = [DNSResolver share];
// Primary: Public cloud DNS
[resolver setAccountId:@"******"
andAccessKeyId:@"********"
andAccesskeySecret:@"********"];
// Backup: On-premises DNS
[resolver setFusionDNSWithIPv4:@[@"1.1.X.X", @"2.2.X.X"]
IPv6:nil
Host:nil
Port:@"443"
HealthCheckDomain:@"check.example.com"
accessKeyId:@"your_fusion_ak"
accesskeySecret:@"your_fusion_sk"];
// Optional: Disable certificate validation (for test environments only).
// [resolver setEnableCertificateValidation:NO];
4. Yerinde birincil, genel cloud yedek
Birincil yerinde DNS başarısız olursa çözümleme otomatik olarak Alibaba Cloud genel HTTPDNS'e yük devreder.
DNSResolver *resolver = [DNSResolver share];
// Primary: On-premises DNS
[resolver setFusionDNSWithIPv4:@[@"1.1.X.X", @"2.2.X.X"]
IPv6:nil
Host:nil
Port:@"443"
HealthCheckDomain:@"check.example.com"
accessKeyId:@"your_fusion_ak"
accesskeySecret:@"your_fusion_sk"];
// Optional: Disable certificate validation (for test environments only).
// [resolver setEnableCertificateValidation:NO];
// Backup: Public cloud DNS
[resolver setAccountId:@"******"
andAccessKeyId:@"********"
andAccesskeySecret:@"********"];
Yeni hizmet API'leri
SDK, yerinde DNS yapılandırması, güvenlik ilkesi denetimi ve otomatik birincil/yedek yük devretme için üç temel API sağlar.
1. Yerinde DNS yapılandırması
/** This is related to on-premises DNS for private deployments. Do not call this method if you only use public DNS.
*
* Sets the on-premises DNS server address and authentication information.
* Use this interface to pass your private DNS server's address and authentication credentials.
* The SDK will use this information to initiate requests.
* @param ipv4 An array of IPv4 addresses (can be nil).
* @param ipv6 An array of IPv6 addresses (can be nil).
* @param host An array of hostnames (can be nil).
* @param port The service port (for example, @"443"). If nil, the default port is used.
* @param healthCheckDomain The domain for health checks after a circuit break. If a resolution service fails more than three consecutive times, the circuit is tripped, and the service IP enters a healthCheck state. Subsequent requests will not use this service. A timer then probes this healthCheckDomain every minute to check if the service is available. If a probe succeeds, the service state is restored to alive and can receive requests again.
* @param accessKeyId Your private accessKeyId for authentication.
* @param accesskeySecret Your private accesskeySecret for authentication.
*/
- (void)setFusionDNSWithIPv4:(NSArray<NSString *> * _Nullable)ipv4
IPv6:(NSArray<NSString *> * _Nullable)ipv6
Host:(NSArray<NSString *> * _Nullable)host
Port:(NSString * _Nullable)port
HealthCheckDomain:(NSString * _Nonnull)healthCheckDomain
accessKeyId:(NSString * _Nonnull)accessKeyId
accesskeySecret:(NSString * _Nonnull)accesskeySecret;
2. TLS sertifika doğrulaması
/** This is related to on-premises DNS for private deployments. Do not call this method if you only use public DNS.
*
* Enable or disable certificate validation for on-premises DNS. The default is YES. If your server is not configured with a domain or IP certificate, you can set this to NO for testing. For production environments, set this to YES to avoid security risks.
* @param enable YES to enable (default), NO to disable.
*/
- (void)setEnableCertificateValidation:(BOOL)enable;
3. Otomatik yük devretme eşiği
/** When both public cloud DNS and on-premises DNS are configured, this sets the number of primary DNS failures that trigger an automatic failover to the backup DNS. If only one type of DNS is configured, do not call this method.
*
* Sets the number of primary DNS failures before automatically failing over to the backup DNS. If only one type of DNS is configured, do not call this method.
* @param fallbackThreshold The number of failures. The default is 4 when public cloud DNS is primary, and 2 when on-premises DNS is primary.
* The valid range is [0-4]. A value of 0 means failover occurs immediately. The maximum is 4.
*/
- (void)setFallbackThreshold:(NSInteger)fallbackThreshold;