Background: I have a spring webapp which every 10 seconds polls a RestController API server for various information like employee information and their task information, and a json response object is returned. This employee status and task information is stored in a backend database and served by the rest api calls to the client browsers.
An example call and response is like:
client javascript:
await getEmployeeInfo();
Returns:
{
"employees": [{
"id": "0001",
"name": "john",
"status": "online",
"tasks": ["task1", "task2"]
},
{
"id": "0002",
"name": "pam",
"status": "out-to-lunch",
"tasks": ["task2", "task3"]
}
]
}
Once the above response is received by the client browser, it is then parsed and displayed graphically on a webpage.
What I want to do:
Instead of polling the server for new information every few seconds, I would rather call the getEmployeeInfo()
API, receive the information, and have the HTTP connection kept open to receive updates if their are any.
What I don't want to do: Hammer the server by polling every few seconds to receive the latest information from the server, even though there hasn't been any updates since the last poll. I could reduce the polling frequency to reduce server load, but then the realtimeness of the information would suffer.
My Question: What technology could I use that would allow me to stop polling the server and have the server give updated information to browser clients only when an update has actually occurred. I would require something that provided two-way information as the browser client updates and displays information.
CodePudding user response:
Both Websockets and SSE (Server Sent Events) can meet your needs. More details in
In your example you will open a web-socket (wss) connection to your backend and then on your frontend you will wait for the backend server to response. Since you are using Spring as a backend and javascript on the frontend you should take a look at: