Answer the question
In order to leave comments, you need to log in
What can be improved in the following code?
I need to get rid of the situation when several queries to the database arrived at once with a short period of time.
If the request has already been executed, then you need to return it from the cache.
I have implemented the following logic:
class QueryResultCache {
List<RequestCacheStruct> requestsCacheList = [];
// Если один и тот же запрос отправлен два раза подряд, то второй точно такой же выполнять нет смысла
Map<int, Future<PostgreSQLResult>> pendingFutures = {};
Future<void> addResultToCache(sqlQuery) async {
if(!pendingFutures.containsKey(sqlQuery.hashCode)) {
pendingFutures.addAll({sqlQuery.hashCode: connection.query(sqlQuery, timeoutInSeconds: 3600)});
print('Query was added to Cache');
}
else {
print('This query is already running');
}
var queryResult = await pendingFutures[sqlQuery.hashCode]; // выполняем отложенную Future
await pendingFutures.remove(sqlQuery.hashCode); // удаляем обработанную Future из списка
var queryObj = RequestCacheStruct(sqlQuery.hashCode, DateTime.now(), queryResult! );
requestsCacheList.add(queryObj);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question