📜 ⬆️ ⬇️

Nginx recipes: asynchronous notifications from PostgreSQL to websocket

To prepare asynchronous notifications from PostgreSQL to websocket, we will need nginx itself and its plugins postgres , push-stream , set-misc . (I gave links to my forks, because I made some changes that I haven’t yet been able to push through to the original repositories. You can also use a ready-made way .)

To connect clients to nginx via websocket, create

location =/websocket { push_stream_subscriber websocket; #    websocket push_stream_channels_path $arg_id; #   websocket    id push_stream_websocket_allow_publish on; #   -    push_stream_client_subscribed_request /subscribe; #        push_stream_client_unsubscribed_request /unsubscribe; #        push_stream_client_publish_request /publish; #         websocket } 

When the client connects to the websocket, we start listening to asynchronous notifications in PostgreSQL

 location =/subscribe { internal; postgres_pass ngx; #    PostgreSQL set_quote_json_str $channel $arg_id; #    postgres_query "listen $channel"; #     } 

When a client disconnects from websocket, stop listening to asynchronous notifications in PostgreSQL
')
 location =/unsubscribe { internal; postgres_pass ngx; #    PostgreSQL set_quote_json_str $channel $arg_id; #    postgres_query "unlisten $channel"; #     } 

When publishing to websocket by client, we do something

 location =/publish { internal; postgres_pass ngx; #    PostgreSQL postgres_query "select now()"; #    PostgreSQL      websocket } 

Also, you can simply send something to the client in the websocket

 location =/publisher { allow 127.0.0.1/16; #     deny all; #     push_stream_channel_info_on_publish off; #         push_stream_publisher; #   push_stream_channels_path $arg_id; #   websocket    id } 

Source: https://habr.com/ru/post/456672/


All Articles