本文整理汇总了Java中org.springframework.web.servlet.mvc.method.annotation.SseEmitter类的典型用法代码示例。如果您正苦于以下问题:Java SseEmitter类的具体用法?Java SseEmitter怎么用?Java SseEmitter使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
SseEmitter类属于org.springframework.web.servlet.mvc.method.annotation包,在下文中一共展示了SseEmitter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createSseEmitter
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
/**
* Creates a {@link SseEmitter} and registers the client in the internal database.
* Client will be subscribed to the provided events if specified.
*
* @param clientId unique client identifier
* @param timeout timeout value in milliseconds
* @param unsubscribe if true unsubscribes from all events that are not provided with
* the next parameter
* @param events events the client wants to subscribe
* @return a new SseEmitter instance
*/
public SseEmitter createSseEmitter(String clientId, Long timeout, boolean unsubscribe,
boolean completeAfterMessage, String... events) {
SseEmitter emitter = new SseEmitter(timeout);
emitter.onTimeout(emitter::complete);
registerClient(clientId, emitter, completeAfterMessage);
if (events != null && events.length > 0) {
if (unsubscribe) {
unsubscribeFromAllEvents(clientId, events);
}
for (String event : events) {
subscribe(clientId, event);
}
}
return emitter;
}
示例2: sendNotification
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
public void sendNotification(String username, Notification notification){
Consumer consumer = this.consumers.findByUsername(username);
notification = notifications.save(notification);
consumer.addNotifications(notification);
consumers.save(consumer);
if (this.subscriptions.containsKey(username)) {
for (SseEmitter sse : this.subscriptions.get(username)) {
try {
sse.send(notification, MediaType.APPLICATION_JSON);
} catch (IOException ex) {
this.logger.warn("Broken SSE Emitter..discarding it...");
}
}
}
}
示例3: removeFromSessionsMap
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
public synchronized void removeFromSessionsMap(SseEmitter session, String dashboardId){
LOGGER.debug("Remove SseEmitter {} to sessions map", dashboardId);
if(!StringUtils.isEmpty(dashboardId)){
List<SseEmitter> dashboardEmitters = emittersPerDashboard.get(dashboardId);
if(dashboardEmitters != null){
dashboardEmitters.remove(session);
if(dashboardEmitters.isEmpty()){
emittersPerDashboard.remove(dashboardId);
}
}
}
}
示例4: getResults
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
@GetMapping("/api/notification/feed")
public ResponseEntity<SseEmitter> getResults() {
if(sseEngine==null){
LOGGER.warn(()->"No SSE Engine available");
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
final Long fLoggedInUserId = getLoggedInUserId();
SseEmitter emitter = sseEngine.getEmitters().get(fLoggedInUserId);
if (emitter == null) {
LOGGER.debug(() -> "Creating new emitter");
SseEmitter fEmitter = emitter = new SseEmitter();
emitter.onCompletion(() -> {
LOGGER.debug(() -> "Emitter completed");
sseEngine.getEmitters().remove(fLoggedInUserId);
});
emitter.onTimeout(() -> {
fEmitter.complete();
});
sseEngine.getEmitters().put(fLoggedInUserId, emitter);
}
return new ResponseEntity<>(emitter, HttpStatus.OK);
}
示例5: createSseEventBuilder
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
public SseEventBuilder createSseEventBuilder() {
SseEventBuilder sseBuilder = SseEmitter.event();
if (!this.event.event().equals(SseEvent.DEFAULT_EVENT)) {
sseBuilder.name(this.event.event());
}
this.event.id().ifPresent(sseBuilder::id);
this.event.retry().map(Duration::toMillis).ifPresent(sseBuilder::reconnectTime);
this.event.comment().ifPresent(sseBuilder::comment);
if (this.convertedValue != null) {
sseBuilder.data(this.convertedValue);
}
else {
sseBuilder.data(this.event.data());
}
return sseBuilder;
}
示例6: subscribe
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
@Transactional
@ApiOperation(value = "Returns success/insuccess.", notes = "This method allows a consumer to subscribe the SSE.")
@RequestMapping(value = "/consumer/subscribe", produces = "text/event-stream")
public ResponseEntity<SseEmitter> subscribe(WebRequest request){
String username = request.getParameter("username");
String password = request.getParameter("password");
Consumer consumer = this.consumers.findByUsername(username);
if (consumer == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} else if (consumer.getPassword().equals(password)) {
return new ResponseEntity<>(this.notificationManager.subscribe(username), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
示例7: progress
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
@GetMapping("/progress/{name}")
SseEmitter progress(@PathVariable String name) {
UUID key = UUID.fromString(name);
SseEmitter emitter = new SseEmitter();
progress.addListener(key, a -> {
try {
emitter.send(a);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
if (a >= 1) {
emitter.complete();
}
});
emitter.onCompletion(() -> progress.removeListener(key));
return emitter;
}
示例8: bindObservable
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
/**
* Binds the supplied observable to the SseEmitter. onNext will call the send method on SseEmitter, the Observable
* subscription will automatically be cancelled when the emitter completes or times out.
* @param emitter SseEmitter
* @param observable Observable that will supply the data
* @return Subscription to the Observable
*/
public static <T> Subscription bindObservable(SseEmitter emitter, Observable<T> observable) {
Subscription subscription = observable.subscribe(new Subscriber<T>() {
@Override
public void onCompleted() {
emitter.complete();
}
@Override
public void onError(Throwable e) {
LOG.warn("Error from stream observable", e);
emitter.completeWithError(e);
}
@Override
public void onNext(T t) {
emitSse(emitter, t);
}
});
bindUnsubscribe(emitter, subscription);
return subscription;
}
示例9: getRealTimeJudgeResultAction
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
/**
* 获取实时的评测结果.
* @param submissionId - 提交记录的唯一标识符
* @return 包含评测结果信息的StreamingResponseBody对象
* @throws IOException
*/
@RequestMapping("/getRealTimeJudgeResult.action")
public SseEmitter getRealTimeJudgeResultAction(
@RequestParam(value="submissionId") long submissionId,
@RequestParam(value="csrfToken") String csrfToken,
HttpServletRequest request, HttpServletResponse response) throws IOException {
User currentUser = HttpSessionParser.getCurrentUser(request.getSession());
boolean isCsrfTokenValid = CsrfProtector.isCsrfTokenValid(csrfToken, request.getSession());
Submission submission = submissionService.getSubmission(submissionId);
if ( !isCsrfTokenValid || submission == null ||
!submission.getUser().equals(currentUser) ||
!submission.getJudgeResult().getJudgeResultSlug().equals("PD") ) {
throw new ResourceNotFoundException();
}
response.addHeader("X-Accel-Buffering", "no");
SseEmitter sseEmitter = new SseEmitter();
submissionEventListener.addSseEmitters(submissionId, sseEmitter);
sseEmitter.send("Established");
return sseEmitter;
}
示例10: submissionEventHandler
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
/**
* 提交事件的处理器.
* @param event - 提交记录事件
* @throws IOException
*/
@EventListener
public void submissionEventHandler(SubmissionEvent event) throws IOException {
long submissionId = event.getSubmissionId();
String judgeResult = event.getJudgeResult();
String message = event.getMessage();
boolean isCompleted = event.isCompleted();
SseEmitter sseEmitter = sseEmitters.get(submissionId);
if ( sseEmitter == null ) {
LOGGER.warn(String.format("CANNOT get the SseEmitter for submission #%d.", submissionId));
return;
}
Map<String, String> mapMessage = new HashMap<>(3, 1);
mapMessage.put("judgeResult", judgeResult);
mapMessage.put("message", message);
sseEmitter.send(mapMessage);
if ( isCompleted ) {
sseEmitter.complete();
removeSseEmitters(submissionId);
}
}
示例11: sendEventUpdateMessage
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
@Override
public void sendEventUpdateMessage(EventType event, String dashboardId) {
List<SseEmitter> emitters = emittersPerDashboard.get(dashboardId);
if(emitters != null){
if(event != EventType.PING) {
sendEventUpdateMessage(EventType.PING, dashboardId);
}
LOGGER.info("Notifying {} dashboards with name {} and event type {}", emitters.size(), dashboardId, event);
for(int i = emitters.size(); i > 0; i--) {
SseEmitter sseEmitter = emitters.get(i-1);
try {
Map<String, String> message = new HashMap<>();
message.put("type", event.getValue());
String jsonMessage = objectMapper.writeValueAsString(message);
sseEmitter.send(jsonMessage, MediaType.APPLICATION_JSON);
} catch (IOException e) {
this.removeFromSessionsMap(sseEmitter, dashboardId);
LOGGER.error("Exception while sending message to emitter for dashboard {}", dashboardId);
}
}
}
}
示例12: send
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
public void send(long id, Object data) throws IOException {
SseEmitter emitter = emitters.get(id);
if (emitter == null) {
LOGGER.warn(() -> "Failed to locate emitter - id=" + id);
} else {
emitter.send(data);
LOGGER.info(() -> "Sent data via emitter - id=" + id);
}
}
示例13: send
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
private void send(SseEmitter emitter, INotification notification) {
new Thread(() -> {
try {
//TODO - Convert to JSON.
emitter.send(notification);
emitter.complete();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
示例14: SseEventStream
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
public SseEventStream(MessageGroup messageGroup, EventSupplier eventSupplier) {
this.eventSupplier = eventSupplier;
this.messageGroup = messageGroup;
this.sseEmitter = new SseEmitter();
this.state = State.READY;
}
示例15: sendAndStopOnError
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; //导入依赖的package包/类
private void sendAndStopOnError(String event, Optional<String> id, Object data) {
try {
SseEventBuilder builder = SseEmitter.event().name(event).data(data);
id.ifPresent(builder::id);
sseEmitter.send(builder);
} catch (Exception e) {
log.warn("Error in SSE channel: " + e);
stop();
}
}