您好,登錄后才能下訂單哦!
signalR+redis分布式聊天服務(wù)器是如何搭建,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
最近在搞一個(gè)直播項(xiàng)目需要聊天服務(wù)器,之前是以小打小鬧來做的,并沒有想太多就只有一臺(tái)服務(wù)器。前幾天一下子突然來了5000人,服務(wù)器瞬間gg,作為開發(fā)人員的我很尷尬! 這就是我們這篇文章的背景。
我使用的是C# Mvc4.0 來開發(fā)的,這里還需要一個(gè)redis 至于你是windows版本還是Linux版本我就不管了,反正是要有個(gè)地址一個(gè)端口,密碼根據(jù)實(shí)際情況填寫。
我這里用一個(gè)demo來展現(xiàn)分布式的情況https://git.oschina.net/908Sharp/signalR-multi-Server.git
第一步:新建兩mvc項(xiàng)目
從nuget 中添加以下幾個(gè)包
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);
}
}
后端就算完成了。
第四步:前端頁面的創(chuàng)建
<div id="chat-content"></div>
<input type="text" id="msg" name="name" value="" placeholder="請(qǐng)輸入聊天內(nèi)容"/>
<input type="button" id="btn" name="name" value="發(fā)送" />
<script src="/Scripts/jquery-1.10.2.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.1.js"></script>
<script src="/Scripts/hub.js"></script>
<script>
/*
signalr
1、初始化聊天服務(wù)器
*/
conn = $.hubConnection();
conn.qs = {
};
conn.start().done(function () {
console.log('signalr success');
$('#btn').click(function () {
var msg = $('#msg').val();
chat.invoke("Chat", msg)
.done(function () {
console.log('signalr send success');
$('#msg').val('');
})
.fail(function (e) {
console.log('signalr send fail');
});
})
});
chat = conn.createHubProxy("chat");
chat.on("Display", function (msg) {
$('#chat-content').html($('#chat-content').html() + '<br/>' + msg)
});
</script>
記住我上面說的demo是兩個(gè)站哦,代碼都一樣的,正式環(huán)境的時(shí)候我們肯定是一份代碼在不同服務(wù)器上部署,指向同一個(gè)redis地址
***我說一下<script src="/Scripts/hub.js"></script> 這個(gè)東西是自動(dòng)生成的,你也可以手動(dòng)指定,我還是把代碼貼出來吧。你也可以F12自己去看。
/*!
* ASP.NET SignalR JavaScript Library v2.2.1
* http://signalr.net/
*
* Copyright (c) .NET Foundation. All rights reserved.
* Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
*
*/
/// <reference path="..\..\SignalR.Client.JS\Scripts\jquery-1.6.4.js" />
/// <reference path="jquery.signalR.js" />
(function ($, window, undefined) {
/// <param name="$" type="jQuery" />
"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));
這一塊是你要是想指定具體路徑也是可以的哦,但是要在后臺(tái)寫這么一句話
看完上述內(nèi)容,你們掌握signalR+redis分布式聊天服務(wù)器是如何搭建的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。