B
B
beduin012021-08-31 19:52:52
Dart
beduin01, 2021-08-31 19:52:52

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);
  }
}


The problem is that it seems to me that the logic is not quite correct (correct if I'm wrong):

- 1st call starts the request and waits.
- 2nd call just starts waiting.
- the request ends.
- 1st call "wakes up" and starts clearing pendingFutures and adding the result to the cache.
- 2nd call "wakes up" and starts clearing pendingFutures and adding the result to the cache.

Right? If yes, how to fix it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question