ra1u / redis-dart

fast redis protocol parser and client
MIT License
84 stars 35 forks source link

Proper way to handle RedisConnection after sending commands #5

Closed nidev closed 7 years ago

nidev commented 7 years ago

First, thank you for great library that made me keep studying Dart with Redis!

Writing codes for wrapper to use like Map object, I made simple Function to deal with async calls: (Part of whole code. If you are interested in it, please watch it at here.)

   Function _redisCommander = (redisCommand) async {
      Command command = await _redis.connect(host, port);

      String authenticate = "OK";
      if (password.isNotEmpty) {
        authenticate = await command.send_object(["AUTH", password]);
      }

      if (authenticate == "OK") {
        return command.send_object(redisCommand);
      }
      else {
        throw new Exception("Incorrect password. Redis access is unauthorized.");
      }
    };

What I wonder is, 'close' may be required when 'connect' exists. And I found function 'close' on connection.dart file. I understood it closes socket connection. But there's no example code calling 'close' after operation.

How do I handle RedisConnection properly? Isn't it necessary to handle RedisConnection manually?

ra1u commented 7 years ago

Nice to hear that you find inspiration in this particular libraray.

In general I had in mind that single connection is used among multiple users/clients. Main idea is that everyone is using same connection. This makes best performance, and requires single connection.

Alternatively, you can write your own wrapper around connector. That is. function/class that takes connection argument and computation to execute. Function opens connection it execute computation and once it is done it closes connection.

Some sketch code.

Future<> RedisConnHadler({String host = "127.0.0.1",
                               int port = 6379, 
                              String password = "", String redisKey = ""}
                              ,var func) {

   //  connect
   conn = new RedisConnection();
   Command command = await  conn.connect(host, port);         
   await auth(command,password);

   // func is expected to have prototype like
   // Future<X> func(Command cmd) or equvalent async
   await func(command);
   await conn.close()
   return Future.value()  // dummy future
}

Use of such interface can go wrong if future returned from func is not last future, that can frequently happen if return is forgotten, but less likely if async is used.

nidev commented 7 years ago

Thanks for your advice. Now, I think i can make different approach. Still a little bit confused about async/await operation.

I'll close this issue as my concern is cleared.