1.在网址【https://github.com/microsoftarchive/redis/releases】进行下载msi文件,下载完毕直接安装即可。
2.安装完毕后,在其安装目录【本人安装在F盘下】添加一个bat文件,内容为
redis-server.exe redis.windows.conf
以便我们双击此批处理命令就能方便启动redis服务端
3.VS2019创建窗体应用程序,框架选用.net framework 4.7.2
4.简单设计一下界面
5.Nuget包安装【ServiceStack.Redis】库
6.添加一个类文件RedisUtil.cs
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedisDemo
{
public class RedisUtil
{
public RedisClient client = null;
///
/// 开启redis服务
///
///
public bool Start()
{
if (Process.GetProcessesByName("redis-server.exe").Length > 0)
{
return false;
}
Process process = new Process();
process.StartInfo.WorkingDirectory = @"F:\Redis";
process.StartInfo.FileName = @"F:\Redis\startup.bat";
process.StartInfo.CreateNoWindow = false;
process.StartInfo.UseShellExecute = false;
process.Start();
return true;
}
///
/// 关闭redis服务
///
///
public bool Close()
{
bool flag = false;
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName.Contains("redis-server"))
{
process.Kill();
flag = true;
}
}
return flag;
}
///
/// 连接redis服务
///
///
public void Connect()
{
if (client == null)
{
client = new RedisClient("127.0.0.1", 6379);
}
}
///
/// 断开连接
///
public void Disconnect()
{
if (client != null)
{
client.Quit();
}
}
///
/// 所有键值对
///
///
public List AllKeyValue()
{
IEnumerable keys = client.ScanAllKeys();
List result = new List();
foreach (string key in keys)
{
string value = "";
string type = client.Type(key).ToLower();
int len;
byte[][] buffer;
switch (type)
{
case "string":
value = client.GetValue(key);
break;
case "hash":
buffer = client.HGetAll(key);
value += "{";
for (int i = 0; i < buffer.Length; i += 2)
{
value += $"{Encoding.UTF8.GetString(buffer[i])}={Encoding.UTF8.GetString(buffer[i + 1])}";
if (i + 2 < buffer.Length)
{
value += ",";
}
}
value += "}";
break;
case "list":
len = (int)client.LLen(key);
buffer = client.LRange(key, 0, len);
value += "[";
for (int i = 0; i < buffer.Length; i++)
{
value += $"{Encoding.UTF8.GetString(buffer[i])}";
if (i + 1 < buffer.Length)
{
value += ",";
}
}
value += "]";
break;
case "set":
buffer = client.SMembers(key);
value += "{";
for (int i = 0; i < buffer.Length; i++)
{
value += $"{Encoding.UTF8.GetString(buffer[i])}";
if (i + 1 < buffer.Length)
{
value += ",";
}
}
value += "}";
break;
case "zset":
len = (int)client.ZCard(key);
buffer = client.ZRange(key, 0, len);
value += "{";
for (int i = 0; i < buffer.Length; i++)
{
value += $"{Encoding.UTF8.GetString(buffer[i])}";
if (i + 1 < buffer.Length)
{
value += ",";
}
}
value += "}";
break;
default:
break;
}
result.Add($"type={type},key={key},value={value}");
}
return result;
}
///
/// 添加
///
///
///
public void Add(T t) where T : IAdd
{
t.Add(client);
}
///
/// 删除
///
///
public void Delete(string key)
{
client.Del(key);
}
///
/// 查询
///
///
///
public string Search(string key)
{
List result = AllKeyValue();
string pattern = $"key={key}";
foreach(string keyvalue in result)
{
if (keyvalue.Contains(pattern))
{
return keyvalue;
}
}
return "";
}
}
public interface IAdd
{
void Add(RedisClient client);
}
public class StringItem : IAdd
{
public string key;
public string value;
public StringItem(string key, string value)
{
this.key = key;
this.value = value;
}
public void Add(RedisClient client)
{
client.Set(key, value);
}
}
public class HashItem : IAdd
{
public string hashId;
public Dictionary pairs = new Dictionary();
public HashItem(string hashId, Dictionary pairs)
{
this.hashId = hashId;
this.pairs = pairs;
}
public void Add(RedisClient client)
{
byte[][] ks = new byte[pairs.Count][];
byte[][] vs = new byte[pairs.Count][];
int i = 0;
foreach (string key in pairs.Keys)
{
ks[i] = Encoding.UTF8.GetBytes(key.ToString());
vs[i] = Encoding.UTF8.GetBytes(pairs[key].ToString());
}
client.HMSet(hashId, ks, vs);
}
}
public class ListItem : IAdd
{
public string listId;
public string value;
public ListItem(string listId, string value)
{
this.listId = listId;
this.value = value;
}
public void Add(RedisClient client)
{
client.LPush(listId, Encoding.UTF8.GetBytes(value));
}
}
public class SetItem : IAdd
{
public string setId;
public string value;
public SetItem(string setId, string value)
{
this.setId = setId;
this.value = value;
}
public void Add(RedisClient client)
{
client.SAdd(setId, Encoding.UTF8.GetBytes(value));
}
}
public class ZSetItem : IAdd
{
public string setId;
public double score;
public string value;
public ZSetItem(string setId, double score, string value)
{
this.setId = setId;
this.score = score;
this.value = value;
}
public void Add(RedisClient client)
{
client.ZAdd(setId, score, Encoding.UTF8.GetBytes(value));
}
}
}
7.给窗体添加事件绑定
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RedisDemo
{
public partial class MainForm : Form
{
readonly RedisUtil util = new RedisUtil();
public MainForm()
{
InitializeComponent();
try
{
}
catch (Exception exception)
{
MessageBox.Show(exception.Message+"\n"+exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
comboBox_Type.SelectedIndex = 0;
}
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
}
catch (Exception exception)
{
MessageBox.Show(exception.Message + "\n" + exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Button_Start_Click(object sender, EventArgs e)
{
try
{
if (util.Start())
{
toolStripStatusLabel.Text = "redis服务端开启成功";
}
else
{
toolStripStatusLabel.Text = "redis服务端开启失败";
}
}
catch (Exception exception)
{
toolStripStatusLabel.Text = "redis服务端开启失败";
MessageBox.Show(exception.Message + "\n" + exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Button_Close_Click(object sender, EventArgs e)
{
try
{
if (util.Close())
{
toolStripStatusLabel.Text = "redis服务端关闭成功";
}
else
{
toolStripStatusLabel.Text = "redis服务端关闭失败";
}
}
catch (Exception exception)
{
toolStripStatusLabel.Text = "redis服务端关闭失败";
MessageBox.Show(exception.Message + "\n" + exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Button_Connect_Click(object sender, EventArgs e)
{
try
{
util.Connect();
toolStripStatusLabel.Text = "redis服务端连接成功";
}
catch (Exception exception)
{
toolStripStatusLabel.Text = "redis服务端连接失败";
MessageBox.Show(exception.Message + "\n" + exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Button_Disconnect_Click(object sender, EventArgs e)
{
try
{
util.Disconnect();
toolStripStatusLabel.Text = "连接断开成功";
}
catch (Exception exception)
{
toolStripStatusLabel.Text = "连接断开失败";
MessageBox.Show(exception.Message + "\n" + exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Button_AllKeyValue_Click(object sender, EventArgs e)
{
try
{
List result = util.AllKeyValue();
richTextBox_AllKeyValue.Clear();
richTextBox_AllKeyValue.AppendText(string.Join("\r\n", result));
toolStripStatusLabel.Text = "查询所有键值对成功";
}
catch (Exception exception)
{
toolStripStatusLabel.Text = "查询所有键值对失败";
MessageBox.Show(exception.Message + "\n" + exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Button_Add_Click(object sender, EventArgs e)
{
try
{
string type = comboBox_Type.Text.Trim();
string id = textBox_Key.Text.Trim();
string value = "";
switch (type)
{
case "string":
value = richTextBox_Value.Text.Trim();
StringItem stringItem = new StringItem(id, value);
util.Add(stringItem);
break;
case "hash":
string[] ps = richTextBox_Value.Text.Trim().Split(' ');
Dictionary pairs = new Dictionary();
for (int i = 0; i < ps.Length; i += 2)
{
pairs.Add(ps[i], ps[i + 1]);
}
HashItem hashItem = new HashItem(id, pairs);
util.Add(hashItem);
break;
case "list":
value = richTextBox_Value.Text.Trim();
ListItem listItem = new ListItem(id, value);
util.Add(listItem);
break;
case "set":
value = richTextBox_Value.Text.Trim();
SetItem setItem = new SetItem(id, value);
util.Add(setItem);
break;
case "zset":
value = richTextBox_Value.Text.Trim();
ZSetItem zSetItem = new ZSetItem(id, 0, value);
util.Add(zSetItem);
break;
}
toolStripStatusLabel.Text = "添加键值对成功";
}
catch (Exception exception)
{
toolStripStatusLabel.Text = "添加键值对失败";
MessageBox.Show(exception.Message + "\n" + exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Button_Search_Click(object sender, EventArgs e)
{
try
{
string key = textBox_Key.Text.Trim();
string value = util.Search(key);
richTextBox_AllKeyValue.Text = value;
toolStripStatusLabel.Text = "查询键值对成功";
}
catch (Exception exception)
{
toolStripStatusLabel.Text = "查询键值对失败";
MessageBox.Show(exception.Message + "\n" + exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Button_Delete_Click(object sender, EventArgs e)
{
try
{
string key = textBox_Key.Text.Trim();
util.Delete(key);
toolStripStatusLabel.Text = "删除键值对成功";
}
catch (Exception exception)
{
toolStripStatusLabel.Text = "删除键值对失败";
MessageBox.Show(exception.Message + "\n" + exception.StackTrace, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
8.项目我已经上传到码云中【CSharp与Redis交互: 使用C#与Redis数据库简单交互,熟悉Redis的使用】,有需要的同学可以自行下载,仅供参考