Modifying the consumer to be fully asynchronous
The ChatConsumer
you have implemented inherits from the synchronous base class WebsocketConsumer
. Synchronous consumers operate in a way that each request must be processed in sequence, one after the other. Synchronous consumers are convenient for accessing Django models and calling regular synchronous I/O functions. However, asynchronous consumers perform better because of their ability to perform non-blocking operations, moving to another task without waiting for the first operation to complete. They don’t require additional threads when handling requests, thus reducing wait times and increasing the ability to scale to more users and requests simultaneously.
Given that you are already using the asynchronous channel layer functions, you can seamlessly rewrite the ChatConsumer
class to make it asynchronous.
Edit the consumers.py
file of the chat
application and implement the following changes:
import json
from channels...