Add a simple DNS caching system to BNetworkAddress

netresolv (and libbind) won't cache DNS requests, which can result in a
lot of DNS requests being made for the same host. Implement a simple
cache in RAM (local to each application) which will keep the most
recently requested addresses cached. This can speed up loading of an
HTTP page a lot, by saving a DNS request for each resource stored on the
same server as the main page.
This commit is contained in:
Adrien Destugues
2015-06-14 15:47:13 +02:00
parent 755f6d2f83
commit f972422c66
3 changed files with 149 additions and 15 deletions
+49 -1
View File
@@ -6,6 +6,9 @@
#define _NETWORK_ADDRESS_RESOLVER_H
#include <ObjectList.h>
#include <Referenceable.h>
#include <String.h>
#include <SupportDefs.h>
@@ -20,7 +23,7 @@ enum {
};
class BNetworkAddressResolver {
class BNetworkAddressResolver: public BReferenceable {
public:
BNetworkAddressResolver();
BNetworkAddressResolver(const char* address,
@@ -53,9 +56,54 @@ public:
status_t GetNextAddress(int family, uint32* cookie,
BNetworkAddress& address) const;
// TODO all the ::Resolve variants are needed. Maybe the SetTo and
// constructors could be removed as ::Resolve is the right way to get a
// resolver (using the cache).
static BReference<const BNetworkAddressResolver> Resolve(
const char* address, const char* service,
uint32 flags = 0);
static BReference<const BNetworkAddressResolver> Resolve(
const char* address, uint16 port = 0,
uint32 flags = 0);
static BReference<const BNetworkAddressResolver> Resolve(int family,
const char* address, const char* service,
uint32 flags = 0);
static BReference<const BNetworkAddressResolver> Resolve(int family,
const char* address, uint16 port = 0,
uint32 flags = 0);
private:
addrinfo* fInfo;
status_t fStatus;
struct CacheEntry {
CacheEntry(int family, const char* address, const char* service,
uint32 flags, BNetworkAddressResolver* resolver)
:
fFamily(family),
fAddress(address),
fService(service),
fFlags(flags),
fResolver(resolver, false)
{
}
bool Matches(int family, BString address, BString service, uint32 flags)
{
return family == fFamily && flags == fFlags && address == fAddress
&& service == fService;
}
int fFamily;
BString fAddress;
BString fService;
uint32 fFlags;
BReference<const BNetworkAddressResolver> fResolver;
};
static BObjectList<CacheEntry> sCacheMap;
};