Reputation: 71
I am writing a web app where multiple listeners(Evcentsource SSE clients JS) will be connected to my server . what i want to do is
Upvotes: 6
Views: 31215
Reputation: 61
To solve the timeout issue, we used Long.MAX_VALUE
as the timeout and it worked perfectly fine.
Upvotes: 2
Reputation: 512
If you want the sseEmmiter available open for infinite time, you can simply set the time out to -1L
and to send events selectively put all of sseEmmiters in a map with specific key to use it when you want to send event like i did in this code .
@Controller
@RequestMapping(path = "api/person")
public class PersonController {
@Autowired
private PersonRepository personRepository;
private Map<String, SseEmitter> onPersonAddedSseEmitters = new ConcurrentHashMap<>();
@PostMapping(path = "/add")
public @ResponseBody
String addPerson(@RequestBody Person person) {
person.setId(new Random().nextLong());
personRepository.save(person);
onPersonAddedSseEmitters.forEach((key, sseEmitter) -> {
try {
if (person.getName().startsWith(key.split("-")[0])) {
sseEmitter.send(person);
}
} catch (Exception ignored) {
sseEmitter.complete();
onPersonAddedSseEmitters.remove(key);
}
});
return "Saved";
}
@GetMapping(path = "/onPersonAdded/{prefix}")
public SseEmitter onPersonAdded(@PathVariable String prefix) {
SseEmitter sseEmitter = new SseEmitter(-1L);
onPersonAddedSseEmitters.put(prefix + "-" + new Random().nextLong(), sseEmitter);
return sseEmitter;
}
}
Upvotes: 10
Reputation: 3889
Details about how you should set a proper timeout. 2 ways of doing this with Spring
SseEmitter emitter = new SseEmitter(15000L); // Example for 15s
spring.mvc.async.request-timeout: 15000
Quote from documentation
By default not set in which case the default configured in the MVC Java Config or the MVC namespace is used, or if that's not set, then the timeout depends on the default of the underlying server.
Upvotes: 4
Reputation: 998
You need to set the timeout on the SseEmitter. The default timeout is rather short.
The SseEmitter timeout is in milliseconds. It is a session timeout, not affected by activity on the session.
The timeout needs to be set to the expected duration of the session, in milliseconds. So, 86400000 (or more) is entirely appropriate.
Upvotes: 6