2

I am attempting to use Redis on Azure for the first time. I tried their sample application which did not work so I tried to make the most minimal example, but I'm still running into an exception. Here is the test code

using StackExchange.Redis;
using System;
using System.Threading.Tasks;

namespace RedisLib
{
    public class Redis
    {
        private ConnectionMultiplexer connection;
        public async Task<string> SaveStringAsync(string key, string value)
        {
            try
            {
                var connectionString = Helpers.Constants.REDIS_CONNECTION_STRING;
                connection = await ConnectionMultiplexer.ConnectAsync(connectionString);

                var database = connection.GetDatabase();
                await database.StringSetAsync(key, value);

                var getValue = await database.StringGetAsync(key);
                await connection.CloseAsync();

                return getValue;
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
                throw;
            }
            finally
            {
                await connection.DisposeAsync();
            }
        }
    }
}

Everything works fine until the await database.StringSetAsync(key, value); at which point the following exception is thrown:

StackExchange.Redis.RedisConnectionException: The message timed out in the backlog attempting to send because no connection became available (5000ms) - Last Connection Exception: It was not possible to connect to the redis server(s). ConnectTimeout, command=SET, timeout: 5000, inst: 0, qu: 0, qs: 0, aw: False, bw: CheckingForTimeout, rs: NotStarted, ws: Idle, in: 0, last-in: 0, cur-in: 0, sync-ops: 0, async-ops: 2, serverEndpoint: .redis.cache.windows.net:6380, conn-sec: n/a, aoc: 0, mc: 1/1/0, mgr: 10 of 10 available, clientName: HQAPEW1C003-AOE(SE.Redis-v2.6.111.64013), IOCP: (Busy=0,Free=1000,Min=16,Max=1000), WORKER: (Busy=0,Free=2047,Min=16,Max=2047), v: 2.6.111.64013 (Please take a look at this article for some common client-side issues that can cause timeouts: https://stackexchange.github.io/StackExchange.Redis/Timeouts) ---> StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s). ConnectTimeout --- End of inner exception stack trace --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at RedisLib.Redis.d__1.MoveNext() in C:\Users\dominick.marciano\Dev\Experimental\Redis Caching\RedisLib\Redis.cs:line 18

and my connection string is <host name>.redis.cache.windows.net,abortConnect=false,ssl=true,allowAdmin=true,password=<primary access key>

Can anyone provide some guidance on why the connection appears to be made successfully, even though the await ConnetionMultipleer.ConnectionAsync(connectionString) does not thrown any exception? Also, I just create the Redis service on Azure today and I am the only one using it so it shouldn't be running out of connections or experiencing any overloads. Could this be a company firewall issue?

TIA for any help/suggestions you can provide.

1
  • using this code able to connect to azureRadis get the Value of key output Commented May 9, 2023 at 1:35

1 Answer 1

0

The error message states that the Redis server connection timed out. Numerous factors, including network problems or wrong connection settings, could be to blame for this. You can attempt the following to fix the problem:

  • Verify that your network can connect to and access the Redis server.

  • Make that the connection string is accurate and contains the proper credentials.

  • Increase the connection's timeout value.

  • To determine if the issue is unique to your present environment, try connecting to the Redis server from a different network or machine.

  • To ensure that the Redis server is reachable from your network, check the firewall settings. Reference:

I have Referred this MSDoc for Azure Cache for Redis and git @eerhardt

enter image description here

To Get the Key

var connectionString = "Connectionstring";

        try
        {
            var connection = ConnectionMultiplexer.Connect(connectionString);
            var database = connection.GetDatabase();

            var key = "myKey";
            var value = database.StringGet(key);

            Console.WriteLine($"Value of key '{key}': {value}");

            connection.Close();
        }
        catch (RedisServerException ex) when (ex.Message.StartsWith("MOVED"))
        {
            var parts = ex.Message.Split(' ');
            var slot = int.Parse(parts[1]);
            var endpoint = parts[2];
            var accessKey = "<access-key>";
            var newConnectionString = $"{endpoint},ssl=True,abortConnect=False,password={accessKey}";
            var newConnection = ConnectionMultiplexer.Connect(newConnectionString);
            var newDatabase = newConnection.GetDatabase();
            var key = "myKey";
            var value = newDatabase.StringGet(key);

            Console.WriteLine($"Value of key '{key}': {value}");

            newConnection.Close();
        }
    }
}

enter image description here Output :

enter image description here

Note :

Initially the value will be null after setting the value it will display.

To set the key

var connectionString = "connection string";

        try
        {
            var connection = ConnectionMultiplexer.Connect(connectionString);
            var database = connection.GetDatabase();

            // Set the value of a key
            var key = "myKey";
            var value = " 866 13.90.202.154:13000";
            database.StringSet(key, value);

            // Get the value of the key and print it to the console
            var retrievedValue = database.StringGet(key);
            Console.WriteLine($"Value of key '{key}': {retrievedValue}");

            // Close the connection
            connection.Close();
        }
        catch (RedisException ex)
        {
            Console.WriteLine($"Redis error: {ex.Message}");
        }
    }
}

Output : enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.