signalR+redis分布式聊天服务器搭建

网友投稿 599 2023-04-28

signalR+redis分布式聊天服务器搭建

signalR+redis分布式聊天服务器搭建

最近在搞一个直播项目需要聊天服务器,之前是以小打小闹来做的,并没有想太多就只有一台服务器。前几天一下子突然来了5000人,服务器瞬间gg,作为开发人员的我很尴尬! 这就是我们这篇文章的背景。

我使用的是C# Mvc4.0 来开发的,这里还需要一个redis 至于你是windows版本还是Linux版本我就不管了,反正是要有个地址一个端口,密码根据实际情况填写。

***步:新建两mvc项目

从nuget 中添加以下几个包

Install-Package Microsoft.AspNet.SignalR

Install-Package Microsoft.AspNet.SignalR.Redis

install-package Microsoft.Owin.Cors

第二步:在App_Start目录中添加Owin StartUp类

public void Configuration(IAppBuilder app)        {            GlobalHost.DependencyResolver.UseRedis("127.0.0.1", 6379, string.Empty, "SignalRBus");            app.Map("/signalr", map =>            {                map.UseCors(CorsOptions.AllowAll);

var hubConfiguration = new HubConfiguration                {                    EnableJSONP = true                };                map.RunSignalR(hubConfiguration);            });        }

注意引用的包啊,骚年们。

第三步:添加ChatHub 类

[HubName("chat")]    public class ChatHub:Hub    {         public void Chat(string msg)        {            Clients.All.Display("Receive Msg:" + msg);        }

}

后端就算完成了。

第四步:前端页面的创建

记住我上面说的demo是两个站哦,代码都一样的,正式环境的时候我们肯定是一份代码在不同服务器上部署,指向同一个redis地址

***我说一下 这个东西是自动生成的,你也可以手动指定,我还是把代码贴出来吧。你也可以F12自己去看。

/// /// (function ($, window, undefined) {    ///     "use strict";

if (typeof ($.signalR) !== "function") {        throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js.");    }

var signalR = $.signalR;

function makeProxyCallback(hub, callback) {        return function () {            // Call the client hub method            callback.apply(hub, $.makeArray(arguments));        };    }

function registerHubProxies(instance, shouldSubscribe) {        var key, hub, memberKey, memberValue, subscriptionMethod;

for (key in instance) {            if (instance.hasOwnProperty(key)) {                hub = instance[key];

if (!(hub.hubName)) {                    // Not a client hub                    continue;                }

if (shouldSubscribe) {                    // We want to subscribe to the hub events                    subscriptionMethod = hub.on;                } else {                    // We want to unsubscribe from the hub events                    subscriptionMethod = hub.off;                }

// Loop through all members on the hub and find client hub functions to subscribe/unsubscribe                for (memberKey in hub.client) {                    if (hub.client.hasOwnProperty(memberKey)) {                        memberValue = hub.client[memberKey];

if (!$.isFunction(memberValue)) {                            // Not a client hub function                            continue;                        }

subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue));                    }                }            }        }    }

$.hubConnection.prototype.createHubProxies = function () {        var proxies = {};        this.starting(function () {            // Register the hub proxies as subscribed            // (instance, shouldSubscribe)            registerHubProxies(proxies, true);

this._registerSubscribedHubs();        }).disconnected(function () {            // Unsubscribe all hub proxies when we "disconnect".  This is to ensure that we do not re-add functional call backs.            // (instance, shouldSubscribe)            registerHubProxies(proxies, false);        });

proxies['chat'] = this.createHubProxy('chat');        proxies['chat'].client = {};        proxies['chat'].server = {            send: function (message) {                return proxies['chat'].invoke.apply(proxies['chat'], $.merge(["send"], $.makeArray(arguments)));            },

sendOne: function (toUserId, message) {                return proxies['chat'].invoke.apply(proxies['chat'], $.merge(["sendOne"], $.makeArray(arguments)));            }        };

return proxies;    };

signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });    $.extend(signalR, signalR.hub.createHubProxies());

}(window.jQuery, window));

这一块是你要是想指定具体路径也是可以的哦,但是要在后台写这么一句话

结束。

我也刚刚写完,还没有放到正式环境去用,哈哈哈,捂嘴偷笑,吐血了吗? 现在我担心我们windows版本的redis不稳定。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:如何在Debian和Ubuntu上安装MariaDB 10
下一篇:数据库权限分配探讨
相关文章