自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

signalR+redis分布式聊天服務(wù)器搭建

開發(fā) 后端 Redis 分布式
最近在搞一個直播項(xiàng)目需要聊天服務(wù)器,之前是以小打小鬧來做的,并沒有想太多就只有一臺服務(wù)器。前幾天一下子突然來了5000人,服務(wù)器瞬間gg,作為開發(fā)人員的我很尷尬! 這就是我們這篇文章的背景。

最近在搞一個直播項(xiàng)目需要聊天服務(wù)器,之前是以小打小鬧來做的,并沒有想太多就只有一臺服務(wù)器。前幾天一下子突然來了5000人,服務(wù)器瞬間gg,作為開發(fā)人員的我很尷尬! 這就是我們這篇文章的背景。

        我使用的是C# Mvc4.0 來開發(fā)的,這里還需要一個redis 至于你是windows版本還是Linux版本我就不管了,反正是要有個地址一個端口,密碼根據(jù)實(shí)際情況填寫。

        我這里用一個demo來展現(xiàn)分布式的情況https://git.oschina.net/908Sharp/signalR-multi-Server.git

        ***步:新建兩mvc項(xiàng)目

        從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);
        }

    }

后端就算完成了。

        第四步:前端頁面的創(chuàng)建

            

<div id="chat-content"></div>
<input type="text" id="msg" name="name" value="" placeholder="請輸入聊天內(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是兩個站哦,代碼都一樣的,正式環(huán)境的時候我們肯定是一份代碼在不同服務(wù)器上部署,指向同一個redis地址

***我說一下<script src="/Scripts/hub.js"></script> 這個東西是自動生成的,你也可以手動指定,我還是把代碼貼出來吧。你也可以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));

 

 

這一塊是你要是想指定具體路徑也是可以的哦,但是要在后臺寫這么一句話

 

結(jié)束。

我也剛剛寫完,還沒有放到正式環(huán)境去用,哈哈哈,捂嘴偷笑,吐血了嗎? 現(xiàn)在我擔(dān)心我們windows版本的redis不穩(wěn)定。

責(zé)任編輯:張燕妮 來源: 開源中國社區(qū)
相關(guān)推薦

2019-03-27 08:43:17

Nginx負(fù)載均衡服務(wù)器

2018-11-07 09:23:21

服務(wù)器分布式機(jī)器學(xué)習(xí)

2015-08-17 09:48:29

C#客戶端分布式緩存

2018-05-31 09:27:38

服務(wù)器架構(gòu)原理

2019-01-28 11:03:03

NginxFastDFS服務(wù)器

2012-07-06 09:27:02

云計算分布式服務(wù)器負(fù)載均衡

2019-06-19 15:40:06

分布式鎖RedisJava

2023-05-29 14:07:00

Zuul網(wǎng)關(guān)系統(tǒng)

2020-03-09 08:24:06

TengineWeb代理服務(wù)器

2014-04-16 09:12:10

2012-02-24 09:27:45

x86服務(wù)器

2023-04-26 08:01:09

分布式編譯系統(tǒng)

2021-11-16 09:38:10

鴻蒙HarmonyOS應(yīng)用

2017-08-10 10:17:32

Hadoop分布式搭建

2014-07-29 09:50:52

Linux處理器分布式服務(wù)器

2019-07-22 09:35:23

RedisSentinel

2023-08-21 19:10:34

Redis分布式

2022-01-06 10:58:07

Redis數(shù)據(jù)分布式鎖

2019-02-18 11:16:12

Redis分布式緩存

2023-09-28 08:59:14

Linux服務(wù)器
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號