英文:
Best way to pass messages between 2 different protocol routes connected to same client
问题
我有一个名为/checkout
的HTTP路由,它会在Zeebe中启动一个工作流程。checkout
路由会立即向调用客户端返回200
响应。然后,工作流程会运行一段时间。为了在完成后将响应推送回客户端,我有一个用于服务器推送事件的独立路由/sse
。在这里,我将在一个全局的map
中存储所有客户端连接。
我的疑问是,我如何找到准确的客户端,以便通过sse
发送响应一次?
- 示例:客户端A正在监听
/sse
并调用/checkout
端点,该端点将返回200。/sse
必须在完成后将响应返回给客户端A。
目前,我考虑使用cookie来标识客户端。是否有更好的方法?
英文:
I have a http route /checkout
which initiates a workflow process in Zeebe. The checkout
route will return 200
response straight-away to calling client. Now, workflow will run for a while. So to push the response back to client after completion, I have a /sse
separate route for server-sent events. Here, I will store all the client connection in a global map
.
My doubt is how do I find the exact client to send the response back through sse
once?
- Example: Client A listening to
/sse
and calls/checkout
endpoint which will return 200. The/sse
has to return the response to client A after completion.
Currently, I thought of using cookie to identify the client. Is there a better way?
答案1
得分: 1
如果您的应用程序已经使用了cookies,那么这是一种可行的方法,因为cookies的目的就是用于识别客户端,所以如果您已经有了cookies,应该使用它。
但是,如果您依赖于其他身份验证机制(比如JWT),您可以将URL用作查询参数。
所以在客户端,不要使用:
let eventSource = new EventSource("/sse");
而是使用:
let eventSource = new EventSource("/sse?authorization=jwt_token");
在后端,您需要验证该令牌,提取客户端ID,并使用该ID访问全局映射以检索相应的连接。
(附注:您应该使用适当的存储方式,如Redis或嵌入式键值存储bbolt,而不是全局映射。)
英文:
If you are already using cookies in your app than that's the way to go since the very purpose of cookies is identifying the client, so if you already have that, you should use it.
But if you rely on another authentication mechanism (like JWT), what you could do is using the url as a query.
So in the client instead of
let eventSource = new EventSource("/sse");
Do
let eventSource = new EventSource("/sse?authorization=jwt_token");
In the backend, you would validate that token, extract the Client ID and hit that global map with it to retrieve the corresponding connection.
(PS: instead of a global map, you should use a proper store, like redis, or an embedded key/value store like bbolt)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论