HostInfoCache: Use QCache.

This commit is contained in:
Nodir Temirkhodjaev 2019-04-15 13:37:02 +05:00
parent 483e031aac
commit 122f1323ae
5 changed files with 43 additions and 14 deletions

View File

@ -58,6 +58,7 @@ SOURCES += \
util/hotkeymanager.cpp \
util/logger.cpp \
util/nativeeventfilter.cpp \
util/net/hostinfo.cpp \
util/net/hostinfocache.cpp \
util/net/hostinfomanager.cpp \
util/net/hostinfoworker.cpp \
@ -122,6 +123,7 @@ HEADERS += \
util/hotkeymanager.h \
util/logger.h \
util/nativeeventfilter.h \
util/net/hostinfo.h \
util/net/hostinfocache.h \
util/net/hostinfomanager.h \
util/net/hostinfoworker.h \

View File

@ -0,0 +1 @@
#include "hostinfo.h"

View File

@ -0,0 +1,15 @@
#ifndef HOSTINFO_H
#define HOSTINFO_H
#include <QObject>
class HostInfo
{
Q_GADGET
Q_PROPERTY(QString hostName MEMBER hostName CONSTANT)
public:
QString hostName;
};
#endif // HOSTINFO_H

View File

@ -4,27 +4,31 @@
HostInfoCache::HostInfoCache(QObject *parent) :
QObject(parent),
m_manager(new HostInfoManager(this))
m_manager(new HostInfoManager(this)),
m_cache(1 * 1024 * 1024)
{
connect(m_manager, &HostInfoManager::lookupFinished,
this, &HostInfoCache::handleFinishedLookup);
m_timer.setSingleShot(true);
m_timer.setInterval(200);
m_triggerTimer.setSingleShot(true);
m_triggerTimer.setInterval(200);
connect(&m_timer, &QTimer::timeout,
connect(&m_triggerTimer, &QTimer::timeout,
this, &HostInfoCache::cacheChanged);
}
QString HostInfoCache::hostName(const QString &address)
{
if (!m_cache.contains(address)) {
m_cache.insert(address, QString());
HostInfo *hostInfo = m_cache.object(address);
if (hostInfo == nullptr) {
hostInfo = new HostInfo();
m_cache.insert(address, hostInfo, 4);
m_manager->lookupHost(address);
return QString();
}
return m_cache.value(address);
return hostInfo->hostName;
}
void HostInfoCache::clear()
@ -38,14 +42,19 @@ void HostInfoCache::clear()
void HostInfoCache::handleFinishedLookup(const QString &address,
const QString &hostName)
{
m_cache.insert(address, hostName);
HostInfo *hostInfo = m_cache.take(address);
if (hostInfo == nullptr)
return;
hostInfo->hostName = hostName;
m_cache.insert(address, hostInfo, hostName.size());
emitCacheChanged();
}
void HostInfoCache::emitCacheChanged()
{
if (!m_timer.isActive()) {
m_timer.start();
if (!m_triggerTimer.isActive()) {
m_triggerTimer.start();
}
}

View File

@ -1,10 +1,12 @@
#ifndef HOSTINFOCACHE_H
#define HOSTINFOCACHE_H
#include <QCache>
#include <QObject>
#include <QHash>
#include <QTimer>
#include "hostinfo.h"
QT_FORWARD_DECLARE_CLASS(HostInfoManager)
class HostInfoCache : public QObject
@ -35,9 +37,9 @@ private:
private:
HostInfoManager *m_manager;
QHash<QString, QString> m_cache;
QCache<QString, HostInfo> m_cache;
QTimer m_timer;
QTimer m_triggerTimer;
};
#endif // HOSTINFOCACHE_H