ra1u / redis-dart

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

Connection cannot be closed #83

Closed zs856 closed 12 months ago

zs856 commented 12 months ago

Hi. I am currently building a Flutter app and making use of the Redis package. I found the connection cannot be closed when I invoke cmd.get_connection().close() until I close the app (Platform: Windows desktop, Edge, and Android app) My flutter verison is: 3.13 Dart Version: Dart SDK version: 3.1.4 (stable) (Tue Oct 17 14:55:53 2023 +0000) on "windows_x64" Redis package version: 4.0.0 Here below is a snippet of codes: In file A, I have a function to create a Command:

//import 'package:flutter/foundation.dart';
import 'package:redis/redis.dart';

Future<Command> createCmd() async {
  Command cmd = await RedisConnection().connect(
      'my-redis-cloud-host', port);
  await cmd.send_object([
    "AUTH",
    "account",
    "secret"
  ]).then((var response) {
    print(response);
  });
  return cmd;
}

In file B, I have other functions to use this Command I created in file A: The function below will be called by 11 elements in a ListView at the same time.

Future<String> readGameRunningState(String gameId) async {
  Command cmd = await createCmd();
  String jobName = await cmd.send_object([
    "GET",
    "key",
  ]);
  await cmd.get_connection().close();
  var logger = Logger();
  logger.d("Connection is closed!: jobName");
  return jobName;

Any suggestion will be helpful. Thank you.

ra1u commented 12 months ago

Hi.

Can you provide more info about where your code gets stuck? In case this code executes, but is not stucked (runs trough close()) I suspect, there must be some other operation that opens, but does not close connection.

Regarding open/close I have just pushed test designed in similar fassion to what you have just described https://github.com/ra1u/redis-dart/commit/23af8c6c7be642043995879bf3e3ebbec2aae0f5. This test runs as expected (it pass), but feel free to modify, so we can learn, if we have indeed bug in this libraray.

Kind regards, Luka

zs856 commented 12 months ago

I figured out the reason now.

Reason

  1. I didn't figure out what send_object might return (a value or a null)
  2. I didn't use the try-catch clause in the async code block so I didn't see any error report.
  3. In my case, send_object executes the GET command and cannot get any matched key so it returns null. Obviously, a null cannot be assigned to a String variable.

    Solution

    change

    String jobName = await cmd.send_object([
    "GET",
    "key",
    ]);

    To

    dynamic jobName = await cmd.send_object([
    "GET",
    "key",
    ]);

    and check whether jobName is null.