Connect to Redis

This lesson demonstrates Redis operations inside WinForms. The logic applies to other project types; WinForms is used only for demonstration purposes.

After you install Redis, it runs as an independent background service. To access it from C# WinForms, you establish a connection much like connecting to a regular database.

The connection‑string configuration shown below is placed inside App.config

1. App.config Configuration

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <!-- Redis connection string -->
    <add name="RedisConnectionString" connectionString="127.0.0.1:6379"/>
    <!-- Short form: connectionString="localhost" uses default port 6379 -->
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>Code language: HTML, XML (xml)

Connection string explanation

  • localhost / 127.0.0.1:Local Redis service
  • Default port 6379;Format for non‑default port:127.0.0.1:6380
  • If Redis is password‑protected:127.0.0.1:6379,password=yourpassword

2. Core Code in Form1.cs

Required NuGet package

StackExchange.Redis

Required namespaces

using StackExchange.Redis;
using System.Configuration;Code language: C# (cs)
public partial class Form1 : Form
{
    // Redis database operation object
    private IDatabase db;
    // Read connection string from config file
    private string ConnectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString;
    // Multiplexed connection (official recommended singleton, volatile for thread‑safety)
    private volatile IConnectionMultiplexer connection;

    public Form1()
    {
        InitializeComponent();
        // Establish connection
        connection = ConnectionMultiplexer.Connect(ConnectionString);
        // Get default database No.0
        db = connection.GetDatabase();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Set method: write cache (key, value, expiration seconds)
        bool res = Set(this.textBox1.Text, this.textBox2.Text, 1000);
        if (res)
        {
            MessageBox.Show("Set succeeded");
        }
        else
        {
            MessageBox.Show("Set failed");
        }
    }

    /// <summary>
    /// Simple wrapper for writing Redis string key‑value pairs
    /// </summary>
    bool Set(string key, object data, int cacheTime)
    {
        if (string.IsNullOrEmpty(key)) return false;
        // Set expiration time
        var expire = TimeSpan.FromSeconds(cacheTime);
        return db.StringSet(key, data.ToString(), expire);
    }
}Code language: C# (cs)

Connect to Redis

Leave a Reply

Your email address will not be published. Required fields are marked *