在C#目前被广泛使用的Redis插件有3个
【CSRedisCore】
【ServiceStack.Redis】
【StackExchange.Redis】
好像ServiceStack.Redis性能最优秀
但是每小时连接数达到6000+要付费
然后StackExchange.Redis稍微差那么一点
但不做限制
最后我选用了CSRedisCore
源于这里
为什么使用CSRedisCore
代码仓库
在VS里面的Nuget里面 下载次数
StackExchange.Redis》ServiceStack.Redis》CSRedisCore
但是我们还是选用CSRedisCore
这就是它了
我需要它做一件什么事情先说一下
看过我写的SuperSocket教程的同学应该知道
我们后面肯定是要对客户端的数据进行收集的
然后我这里想使用Redis来做这件事情
当然没有源码的也不要慌
我会把这个项目最后的源码上传 供下载
可以在我的资源文件找到
好的那我们开始吧
导入后如何使用CSRedisCore呢
很简单
在我们的APPServer里面
加入进来
代码如下
using CSRedis;
using Socket.appReceive;
using Socket.appSession;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Socket.appServer
{
public class MyAppServer : AppServer<MyAppSession>
{
private CSRedisClient redis;
private static int LoopRecordNum = 0;
protected override void OnStopped()
{
base.OnStopped();
}
protected override void OnStarted()
{
redis = new CSRedisClient("127.0.0.1:6379,password=12345678,defaultDatabase=0");
RedisHelper.Initialization(redis);
Console.WriteLine("MyAppServer启动成功");
this.NewRequestReceived += new RequestHandler<MyAppSession, StringRequestInfo>(appServer_NewRequestReceived);
Task.Factory.StartNew(() => {
while (true)
{
Thread.Sleep(5000);
if (this.GetAllSessions() != null)
{
foreach (var item in this.GetAllSessions())
{
item.Send("hello");
}
}
else
{
Console.WriteLine("无客户端连接");
}
}
});
//base.OnStarted();
}
protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
{
return base.Setup(rootConfig, config);
}
private static void appServer_NewRequestReceived(MyAppSession session, StringRequestInfo requestInfo)
{
try
{
int flag = 0;
switch (requestInfo.Key.ToUpper())
{
case ("ECHO"):
if (requestInfo.Body.Contains("hello"))
{
session.Send("hi my name is Server");
flag++;
}
else
{
session.Send("ninainaider");
flag++;
}
break;
case ("ADD"):
new ADD().ExecuteCommand(session, requestInfo);
flag++;
break;
case ("MULT"):
new MULT().ExecuteCommand(session, requestInfo);
flag++;
break;
}
if (flag == 0)
{
Console.WriteLine(requestInfo.Key + requestInfo.Body);
RedisHelper.Set(requestInfo.Key+LoopRecordNum++, requestInfo.Body);
Console.WriteLine(LoopRecordNum);
}
}
catch (Exception)
{
Console.WriteLine("异常");
}
}
}
}
大概就这写地方稍微做了下改动
然后我们运行
打开三个客户端连接服务器
开始发送 嘟嘟嘟嘟嘟嘟
速度相当的块呀 一秒钟300条数据
stop
停止发送后 我们可以看到存了8000多条到redis
现在我们来新建一个控制台
看这些存入到redis没有
和我们存入的数据是一样的
这样就把我们的程序和redis联系起来拉
这是最简单的方式哦
然后看一下redisHelper类
功能太多 这篇不做解释
反正用就完了