精华内容
下载资源
问答
  • channels

    2020-04-01 17:31:46
    https://channels.readthedocs.io/en/latest/tutorial/part_2.html frontConsumer and MQConsumer to same named channel group

    https://channels.readthedocs.io/en/latest/tutorial/part_2.html

     

    frontConsumer and MQConsumer to same named channel group

    展开全文
  • Channels

    2017-01-31 00:40:00
    Introducing Channels _channel_对象代表了一个开放连接到能够执行IO操作的硬件设备,如文件,网络流,应用组件。_channel_使用_buffer_作为一个传输数据载体。 Channel and Its Children 所有_channel_类都是java....

    Introducing Channels

    _channel_对象代表了一个开放连接到能够执行IO操作的硬件设备,如文件,网络流,应用组件。_channel_使用_buffer_作为一个传输数据载体。

    Channel and Its Children

    所有_channel_类都是java.nio.channels.Channel接口的实现类。它声明了两个方法:

    • void close():关闭_channel_
    • boolean isOpen():检查_channel_是否开启着

    所有_channel_都共用这两个方法,为了支持IO操作,有两个扩展接口:

    • WritableByteChannle
    • ReadableByteChannel

    以上两个接口都是单向接口(只读或只写),java提供了java.nio.channels.ByteChannel接口,该接口是同时支持读写操作。

    java还提供了支持异步关闭的java.nio.channels.InterruptibleChannel,实现该接口的_channel_具有异步关闭的功能:当一个线程阻塞在io操作上时,其它线程可以关闭该线程,然后该线程会抛出AsynchronousCloseException。该接口也是可中断的,即其它线程触发该线程的interrupt()方法,会抛出ClosedByInterruptException

    两种获得_channel_实例的方法:

    • 使用Channels工具类
    • 通过经典的IO类来获得。

    一个例子:

    public class UsingChannel {
        @Test
        public void i2o() throws Exception {
            ReadableByteChannel rbc = Channels.newChannel(System.in);
            WritableByteChannel wbc = Channels.newChannel(System.out);
            copy(rbc, wbc);
        }
    
        /**
         * 最少的IO操作次数
         * 
         * @param rbc
         * @param wbc
         * @throws IOException
         */
        void copy(ReadableByteChannel rbc, WritableByteChannel wbc) throws IOException {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int read;
            while ((read = rbc.read(buffer)) != -1) {
                buffer.flip();
                wbc.write(buffer);
                buffer.compact();
            }
            buffer.flip();
            while (buffer.hasRemaining()) {
                wbc.write(buffer);
            }
        }
    
        /**
         * 消除数据的复制移动
         * 
         * @param rbc
         * @param wbc
         * @throws IOException
         */
        void copy2(ReadableByteChannel rbc, WritableByteChannel wbc) throws IOException {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (rbc.read(buffer) != -1) {
                buffer.flip();
                while (buffer.hasRemaining()) {
                    wbc.write(buffer);
                }
                buffer.clear();
            }
        }
    }
    

    Channels in Depth

    Scatter/Gather I/O

    提供一个IO操作横跨多个_buffer_的能力。

    一个例子:

        public void scga() throws Exception {
            final int M_size = 1024 * 1024;
            FileInputStream fis = new FileInputStream("./pdf");
            FileOutputStream fos = new FileOutputStream("./pdfc");
            ScatteringByteChannel src = (ScatteringByteChannel) Channels.newChannel(fis);
            // 这样工作
            // ByteBuffer[] buffers = new ByteBuffer[] {
            // ByteBuffer.allocate(M_size), ByteBuffer.allocate(M_size),
            // ByteBuffer.allocate(M_size) };
    
            // 这样不工作
            ByteBuffer[] buffers = new ByteBuffer[3];
            for (ByteBuffer byteBuffer : buffers) {
                byteBuffer = ByteBuffer.allocate(M_size);
            }
            for (ByteBuffer byteBuffer : buffers) {
                if (byteBuffer == null) {
                    System.out.println("foreach can't assign value");
                    return;
                }
            }
    
            // 这样工作
            // for (int i = 0; i < buffers.length; i++) {
            // buffers[i] = ByteBuffer.allocate(M_size);
            // }
            src.read(buffers);
            src.close();
            for (ByteBuffer byteBuffer : buffers) {
                byteBuffer.flip();
            }
            GatheringByteChannel dest = (GatheringByteChannel) Channels.newChannel(fos);
            dest.write(buffers);
            dest.close();
        }

    这里发现一个我从来都没考虑过的点:foreach的使用,使用foreach时最好是仅取值,而不更新。切记切记!!!

    File Channels

    抽象类java.nio.channels.FileChannel用于描述一个文件通道。因为该类实现了InterruptibeChannel,该类是可中断的,该类同时实现了ByteChannelGatheringByteChannelScatteringByteChannel接口。

    文件通道是线程安全的!

    FileChannel提供了如下方法:

    Method Description
    void force(boolean metadata) 将文件的所有更新都提交到存储设备
    long position() 返回文件指针的位置
    FileChannel position(long newPosition) 指定文件指针的
    int read(ByteBuffer buffer)
    int read(ByteBuffer buffer,long position) 指定开始读取的位置
    long size()
    FileChannel truncate(long size) 截断文件,size是指文件指针的位置,即将文件指针后的文件截断抛弃掉。
    int write(ByteBuffer buffer)
    int write(ByteBuffer buffer, long position)

    Locking Files

    将一个文件锁定或部分锁定是一个重要的特性,但是知道Java1.4,java才支持该功能。这个功能使得JVM进程独占该文件或部分文件,知道该jvm进程释放文件锁。

    尽管我们可以锁定整个文件,但通常最好是锁住一小部分。例如,数据库系统可能会锁住单独的表的一行,而不是整个表,以使其它部分能供外部操作,从而提高吞吐量。

    每一个文件锁开始于文件的特定的字节位置,然后占据一定长度的字节。文件锁协调进程访问不同的文件区域。

    有两种类型的文件锁,排他锁和共享锁。排他锁使得单个写进程,写入到文件,它禁止额外的文件锁同时应用到该区域。共享锁允许多个读进程,同时读取同一个文件区域,它不会禁止其它的共享锁应用到该区域,但是不允许排他锁应用到该问题。

    文件锁属于进程锁,而不是线程锁,因此,同一个jvm进程实例下的线程时共享该文件锁的,这要注意。

    FileChannel声明了四个方法用于获取排他锁或共享锁:

    • FileLock lock():阻塞方法,可能抛出ClosedChannelExceptionNonWritableChannelExceptionOverlappingFileLockExceptionFileLockInterruptionExceptionAsynchronousCloseException异常。
    • FileLock lock(long position, long size, boolean shared):
    • FileLock tryLock():非阻塞方式的,不管成功与否,立即返回。

    以上方法它们每一个都返回一个FileLock对象实例,该对象封装了文件某个区域的锁。该对象具有如下方法:

    • FileChannel channel():返回该文件锁对应的文件通道对象
    • void close():会调用ralease()方法释放锁
    • boolean isShared():判断是否是共享锁
    • boolean isValid():是否有效
    • boolean overlaps(long position, long size):判断文件锁锁定的区域与指定的区域重合
    • long position():返回文件锁相对于文件的开始位置
    • void release():释放文件锁
    • long size():返回文件锁锁定的区域大小
    • String toString():文件锁的信息

    尽管文件锁与文件通道关联,当实际上文件锁是与文件通道相关的具体文件相关的。如果不当心,就会进入竞争状态,甚至是死锁。因此,要总是记得释放锁。

    转载于:https://www.cnblogs.com/xiaojintao/p/6358572.html

    展开全文
  • CHANNELS-源码

    2021-03-17 19:11:45
    CHANNELS
  • Broadcast Channels

    2018-11-03 17:43:21
    Thus several different channels with a common input alphabet are specified. We shall determine the families of simultaneously achievable transmission rates for many extreme classes of channels. Upper...
  • channels java_Channels Class

    2021-03-07 17:28:29
    Channels ClassDefinitionAssembly:Mono.Android.dllThis class provides several utilities to get I/O streams from channels.In this article[Android.Runtime.Register("java/nio/channels/Channels", ApiSince=...

    Channels Class

    Definition

    Assembly:Mono.Android.dll

    This class provides several utilities to get I/O streams from channels.

    In this article

    [Android.Runtime.Register("java/nio/channels/Channels", ApiSince=1, DoNotGenerateAcw=true)]

    public sealed class Channels : Java.Lang.Object

    type Channels = class

    inherit Object

    Inheritance

    Remarks

    Portions of this page are modifications based on work created and shared by the

    Properties

    Returns the unique instance of Class that represents this

    object's class.

    (Inherited from Object)

    The handle to the underlying Android instance.

    (Inherited from Object)

    This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

    (Inherited from Object)

    This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

    (Inherited from Object)

    Methods

    Creates and returns a copy of this Object.

    (Inherited from Object)

    (Inherited from Object)

    Compares this instance with the specified object and indicates if they

    are equal.

    (Inherited from Object)

    Returns an integer hash code for this object.

    (Inherited from Object)

    Invoked when the garbage collector has detected that this instance is no longer reachable.

    (Inherited from Object)

    Returns an input stream on the given channel.

    Returns an output stream on the given channel.

    Returns a readable channel on the given input stream.

    Returns a reader that decodes bytes from a channel.

    Returns a writable channel on the given output stream.

    Returns a writer that encodes characters with the specified

    encoder and sends the bytes to the specified channel.

    Returns a writer that encodes characters with the specified

    encoder and sends the bytes to the specified channel.

    Causes a thread which is waiting on this object's monitor (by means of

    calling one of the wait() methods) to be woken up.

    (Inherited from Object)

    Causes all threads which are waiting on this object's monitor (by means

    of calling one of the wait() methods) to be woken up.

    (Inherited from Object)

    Returns a string containing a concise, human-readable description of this

    object.

    (Inherited from Object)

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

    (Inherited from Object)

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the

    specified timeout expires.

    (Inherited from Object)

    Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the

    specified timeout expires.

    (Inherited from Object)

    Explicit Interface Implementations

    Extension Methods

    Applies to

    展开全文
  • Cov channels

    2020-12-08 18:55:23
    <div><p>the changes made recently in terms of excluding bad channels have caused a regression in covariance calculation. <p>Due to how inverse calculations are coded (and for backward compatibility ...
  • unlimited channels

    2020-11-22 01:13:27
    <div><p>can you please add an option for modpack creator to disable the channels or add a cable with unlimited channels?</p><p>该提问来源于开源项目:AppliedEnergistics/Applied-Energistics-2</p>...
  • django channels

    2019-05-08 16:40:00
    参考文档:https://channels.readthedocs.io/en/latest/index.html pip3 install django ...创建channels库根路由配置文件,根路由配置文件类似Django URLconf,它会告诉Channels当收到由Channes服务器发过来...
    pip3 install django
    pip3 install channels
    安装django及channels

    创建channels库根路由配置文件,根路由配置文件类似Django URLconf,它会告诉Channels当收到由Channes服务器发过来的Http请求时,应该执行什么代码:

    # wssite/routing.py
    from channels.routing import ProtocolTypeRouter
    
    application = ProtocolTypeRouter({
        # (http->django views is added by default)
    })

    将 Channels 库添加到已安装的应用程序列表中。编辑 wssite/settings.py 文件并将 'channels' 添加到 INSTALLED_APPS 设置:

    # mysite/settings.py
    INSTALLED_APPS = [
        'channels',
        'chat',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]

    配置根路由指向 Channels:

    # wssite/settings.py
    # Channels
    ASGI_APPLICATION = 'wssite.routing.application'

    现在已安装的应用程序中有 Channels, 它将控制 runserver 命令, 用 Channels 开发服务器替换标准的 Django 开发服务器。

    consumer配置

    在app中创建新文件consumer,并添加如下代码:

    # app/consumers.py
    from channels.generic.websocket import WebsocketConsumer
    import json
    
    class ChatConsumer(WebsocketConsumer):
        def connect(self):
            self.accept()
    
        def disconnect(self, close_code):
            pass
    
        def receive(self, text_data=None, bytes_data=None):
            text_data_json = json.loads(text_data)
            message = text_data_json['message']
    
            self.send(text_data=json.dumps({
                'message': message

    这是一个同步 WebSocket consumer, 它接受所有连接, 接收来自其客户端的消息, 并将这些消息回送到同一客户端。现在, 它不向同一个房间的其他客户端广播消息。

    Channels 还支持编写异步 consumers 以提高性能。但是, 任何异步 consumers 都必须小心, 避免直接执行阻塞操作。

    我们需要为 app 创建一个路由配置, 它有一个通往 consumer 的路由。创建新文件 app/routing.py。并写入以下代码:

    # app/routing.py
    from django.conf.urls import url
    
    from . import consumers
    
    websocket_urlpatterns = [
        url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
    ]

    下一步是将根路由指向 chat.routing 模块。在 mysite/routing.py 中, 导入 AuthMiddlewareStack、URLRouter 和 chat.routing ;并在 ProtocolTypeRouter 列表中插入一个 "websocket" 键, 格式如下:

    # app/routing.py
    from channels.auth import AuthMiddlewareStack
    from channels.routing import ProtocolTypeRouter, URLRouter
    import chat.routing
    
    application = ProtocolTypeRouter({
        # (http->django views is added by default)
        'websocket': AuthMiddlewareStack(
            URLRouter(
                chat.routing.websocket_urlpatterns
            )
        ),
    })

    这个根路由配置指定,当与 Channels 开发服务器建立连接的时候, ProtocolTypeRouter 将首先检查连接的类型。如果是 WebSocket 连接 (ws://或 wss://), 则连接会交给 AuthMiddlewareStack。

    AuthMiddlewareStack 将使用对当前经过身份验证的用户的引用来填充连接的 scope, 类似于 Django 的 AuthenticationMiddleware 用当前经过身份验证的用户填充视图函数的请求对象。然后连接将被给到 URLRouter。

    根据提供的 url 模式, URLRouter 将检查连接的 HTTP 路径, 以将其路由指定到到特定的 consumer。

    channel layer

    channel layer 是一种通信系统。它允许多个 consumer 实例互相交谈, 以及与 Django 的其他部分进行通信。

    channel layer 提供以下抽象:

      channel 是可以发送消息的邮箱。每个 channel 都有一个名称。任何有名称的 channel 都可以向 channel 发送消息。

      group 是一组相关的 channels。group 具有名称。任何具有名字的 group 都可以按名称向 group 中添加/删除 channel, 也可以向 group 中的所有 channel 发送消息。无法列举特定 group 中的 channel。

    每个 consumer 实例都有一个自动生成的唯一的 channel 名称, 因此可以通过 channel layer 进行通信。

    使用redis作为channel layer的后备存储。

    安装 channels_redis, 以便 Channels 知道如何调用 redis。运行以下命令:

    pip3 install channels_redis

    在使用 channel layer 之前, 必须对其进行配置。编辑 wssite/settings.py 文件并将 CHANNEL_LAYERS 设置添加到底部:

    # wssite/settings.py
    # Channels
    ASGI_APPLICATION = 'mysite.routing.application'
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels_redis.core.RedisChannelLayer',
            'CONFIG': {
                "hosts": [('127.0.0.1', 6379)],
            },
        },
    }

    现在我们有了一个 channel layer, 让我们在 ChatConsumer 中使用它。将以下代码放在 chat/consumers.py 中, 替换旧代码:

    # app/consumers.py
    from asgiref.sync import async_to_sync
    from channels.generic.websocket import WebsocketConsumer
    import json
    
    class ChatConsumer(WebsocketConsumer):
        def connect(self):
            self.room_name = self.scope['url_route']['kwargs']['room_name']  # scope中包含有关其连接的信息且在app/routes.py中的url路由中获取'room_name'参数
            self.room_group_name = 'chat_%s' % self.room_name # 构建channels_group名称
    
            # Join room group
            async_to_sync(self.channel_layer.group_add)(
                self.room_group_name,
                self.channel_name
            )
    
            self.accept() # 用于接受websocket连接,不调用则表示拒绝接收连接
    
        def disconnect(self, close_code):
            # Leave room group
            async_to_sync(self.channel_layer.group_discard)(
                self.room_group_name,
                self.channel_name
            )
    
        # Receive message from WebSocket
        def receive(self, text_data=None, bytes_data=None):
            text_data_json = json.loads(text_data)
            message = text_data_json['message']
    
            # Send message to room group
            async_to_sync(self.channel_layer.group_send)(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': message
                }
            )
    
        # Receive message from room group
        def chat_message(self, event):
            message = event['message']
    
            # Send message to WebSocket
            self.send(text_data=json.dumps({
                'message': message
            }))

    异步模式

    重写 ChatConsumer 使其变为异步的。在 app/consumers.py 中输入以下代码:

    # app/consumers.py
    from channels.generic.websocket import AsyncWebsocketConsumer
    import json
    class ChatConsumer(AsyncWebsocketConsumer):
        async def connect(self):
            self.room_name = self.scope['url_route']['kwargs']['room_name']
            self.room_group_name = 'chat_%s' % self.room_name
    
            # Join room group
            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )
    
            await self.accept()
    
        async def disconnect(self, close_code):
            # Leave room group
            await self.channel_layer.group_discard(
                self.room_group_name,
                self.channel_name
            )
    
        # Receive message from WebSocket
        async def receive(self, text_data):
            text_data_json = json.loads(text_data)
            message = text_data_json['message']
    
            # Send message to room group
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': message
                }
            )
    
        # Receive message from room group
        async def chat_message(self, event):
            message = event['message']
    
            # Send message to WebSocket
            await self.send(text_data=json.dumps({
                'message': message
            }))

    这些用于 ChatConsumer 的新代码与原始代码非常相似, 它们具有以下差异:

    • 现在 ChatConsumer 继承自 AsyncWebsocketConsumer 而不是 WebsocketConsumer。
    • 所有方法都是 async def, 而不仅仅是 def。
    • await 被用于调用执行 I/O 的异步函数。
    • 在 channel layer 上调用方法时, 不再需要 async_to_sync。

    数据库访问

    Django ORM是一段同步代码,因此如果您想从异步代码访问它,您需要进行特殊处理以确保其连接正确关闭。

    如果你正在使用SyncConsumer或者基于它的任何东西 - 比如 JsonWebsocketConsumer- 你不需要做任何特别的事情,因为所有代码都已经在同步模式下运行,并且Channels将作为SyncConsumer代码的一部分为你做清理工作

    但是,如果要编写异步代码,则需要使用安全的同步上下文调用数据库方法database_sync_to_async

    数据库连接

    如果您使用线程使用者(同步的),通道可能会比您可能使用的通道打开更多的数据库连接 - 每个线程最多可以打开一个连接。

    默认情况下,线程数设置为“CPU数* 5”,因此您可以看到最多这个线程数。如果要更改它,请将ASGI_THREADS环境变量设置为您希望允许的最大数量。

    为了避免在连接中有太多线程空闲,您可以改写代码以使用异步使用者,并且只在需要使用Django的ORM(使用database_sync_to_async时才进入线程

    database_sync_to_async 

    要使用它,请在单独的函数或方法中编写ORM查询,然后database_sync_to_async像这样调用它

    from channels.db import database_sync_to_async
    
    async def connect(self):
        self.username = await database_sync_to_async(self.get_name)()
    
    def get_name(self):
        return User.objects.all()[0].name

    您也可以将它用作装饰者:

    from channels.db import database_sync_to_async
    
    async def connect(self):
        self.username = await self.get_name()
    
    @database_sync_to_async
    def get_name(self):
        return User.objects.all()[0].name

     

     

    转载于:https://www.cnblogs.com/yangjintao/p/10832800.html

    展开全文
  • m trying to set up GraphQL Subscriptions with Django Channels 2, but the code keeps on throwing this error: ModuleNotFoundError: No module named 'channels.generic.websockets' <h3>What I Did ...
  • channels-api:具有Django Rest Framework和Channels的RESTful Websocket API
  • ve run into an issue with creating new channels and receiving the <code>reached the maximum number of channels 65535</code> when attempting to create a new channel. <p>After some digging, I noticed ...
  • Water channels

    2017-12-03 10:28:28
    The only way is to build some NEW channels to connect the towns that in drought to the reservoir directly or indirectly. Now the problem is the mayor wants to konw what is the least number of ...
  • django-channels-源码

    2021-03-06 14:54:05
    django-channels
  • Water channels

    2017-11-15 12:02:50
    The only way is to build some NEW channels to connect the towns that in drought to the reservoir directly or indirectly. Now the problem is the mayor wants to konw what is the least number of ...
  • <div><p>Is it possible to convert model from channels_first to channels_last(default Tensorflow tensor dim ordering)?</p><p>该提问来源于开源项目:nerox8664/pytorch2keras</p></div>
  • New communication channels

    2021-01-08 19:42:27
    <div><p>This RFC proposes adding official gitter and Slack channels to compliment our official IRC channels. <p><a href=...
  • <div><h3>Deleting channels <p>What about unused, empty channels? <p>My app's channels can multiply very fast, keeping less than 10 connections and getting useless at the end of a brief session. I ...
  • FastoTV common channels

    2020-12-01 16:01:51
    am developer of <a href="https://github.com/fastogt/fastotv">FastoTV (opensource iptv solution), the main goal in FastoTV project was give ability user to select which channels he want to see in ...
  • Hide settled channels

    2020-12-08 18:13:18
    <p>Opening and closing channels would mean that the UI will show all channels the user created. This issue is to suggest we add some UI utility which would enable me to toggle (show/hide) settled ...
  • channels部署

    千次阅读 2019-01-17 19:40:28
    注意:channels安装完毕后,Daphne已经被附带安装成功,但是不能直接执行daphne,需要自己创建连接. 版本 Django 2.0.7, uWSGI 2.0.17.1,redis 3.2.10, channels 2.1.2, chanels-redis 2.2.1, daphne 2.2.1 前端 ...
  • <div><p>If an Hott-RX like Gr-12L is bound to an Hott-Tx as MC-32, the RX outputs all 16 Channels on SBus. If the same RX is bound to MPM, it outputs only 12 Channels as documented. <p>Is it possible ...
  • Golang channels implementaion
  • <div><p>when i list my open channels i see channels, but don't understand the color coding and icons. <p>2 channels are red, and one of those has a blue dot by it. The other two are white. <p>I ...
  • Django Channels

    2019-05-21 15:13:00
    Django Channels 转载于:https://www.cnblogs.com/niuu/p/10899955.html

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 41,548
精华内容 16,619
关键字:

channels