简体   繁体   中英

How do I handle communication between multiple Node.js servers for each user?

I'm trying to make a user log in just once, and have his information on all the servers. Any changes made to the user's information will instantly be available for all servers. Is this possible to do without having each user "log in" separately for each server?

Sort of like the $_SESSION for php, but for Node.js

Design 1 -

What I think would be best to do, but don't know how to share socket data between servers, perhaps using something like PHP's $_SESSION ? 设计1

Design 2 -

What I'm currently doing:

  1. User uses socket.emit to main.js
  2. main.js adds user information onto the emit
  3. main.js emits to the appropriate server
  4. Appropriate server emits back to main.js
  5. main.js finally emits back to user

This seems awfully inefficient and feels wrong

设计2

If your information is primarily static, you can try something similar to JWT . These are cryptographically signed tokens that your authenticating server can provide and the user can carry around. This token may contain information about the user that you want each server to have available without having the user accessing it.

If it's not, you may be looking into sharing a database across all servers, and have that be the point of synchronization between them.


Updates based on our comments (so they can be removed later):

If you decide to use auto-contained JWT tokens, you don't need to be making trips to the database at all. These tokens will contain all the information required, but it will be transparent to the end user that won't have insight into their contents.

Also, once you understand the JWT standard, you don't necessarily have to work with JSON objects, since it is just the serialization approach that you can switch by another one.

You'd provide one of these tokens to your user on authentication (or whenever required), and then you'd require that user to provide that token to the other servers when requesting information or behavior from them. The token will become your synchronization approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM