All Projects → ralscha → Sse Eventbus

ralscha / Sse Eventbus

Licence: apache-2.0
EventBus library for sending events from a Spring appliction to the web browser with SSE

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Sse Eventbus

Dynamic Data Source Demo
基于事务的读写分离
Stars: ✭ 43 (-27.12%)
Mutual labels:  spring
Company Structure
A company structure with a list of projects and their users
Stars: ✭ 48 (-18.64%)
Mutual labels:  spring
Multi Tenant Spring Mongodb
Stars: ✭ 53 (-10.17%)
Mutual labels:  spring
Disconf Spring Boot Starter
disconf-spring-boot-starter 让你可以使用spring-boot的方式开发依赖disconf的程序 只需要关心disconfi的配置文件和配置项,省略了编写xml的麻烦
Stars: ✭ 44 (-25.42%)
Mutual labels:  spring
Blog demos
CSDN博客专家程序员欣宸的github,这里有四百多篇原创文章的详细分类和汇总,以及对应的源码,内容涉及Java、Docker、Kubernetes、DevOPS等方面
Stars: ✭ 1,030 (+1645.76%)
Mutual labels:  spring
Aws Serverless Java Container
A Java wrapper to run Spring, Jersey, Spark, and other apps inside AWS Lambda.
Stars: ✭ 1,054 (+1686.44%)
Mutual labels:  spring
Mica Example
mica 演示项目
Stars: ✭ 42 (-28.81%)
Mutual labels:  spring
Hrrs
Record, transform, and replay HTTP requests in Java EE and Spring applications.
Stars: ✭ 54 (-8.47%)
Mutual labels:  spring
Spring Cloud Study
开源书《跟我学Spring Cloud》的配套代码。讨论QQ群:731548893
Stars: ✭ 1,036 (+1655.93%)
Mutual labels:  spring
Lectures
Lecture scripts and slides I use during the Software Engineering course at TU Dresden
Stars: ✭ 52 (-11.86%)
Mutual labels:  spring
Mini Platform
Mini-Platform致力于更简洁易用的轻量级微服务治理平台。
Stars: ✭ 45 (-23.73%)
Mutual labels:  spring
Ward
Server dashboard
Stars: ✭ 1,026 (+1638.98%)
Mutual labels:  spring
Spring Statemachine
Spring Statemachine is a framework for application developers to use state machine concepts with Spring.
Stars: ✭ 1,058 (+1693.22%)
Mutual labels:  spring
Esper
📻 Event Source powered by hyper written in Rust
Stars: ✭ 43 (-27.12%)
Mutual labels:  server-sent-events
React Soft Slider
Simple, fast and impartial slider
Stars: ✭ 54 (-8.47%)
Mutual labels:  spring
Activiti
Activiti is a light-weight workflow and Business Process Management (BPM) Platform targeted at business people, developers and system admins. Its core is a super-fast and rock-solid BPMN 2 process engine for Java. It's open-source and distributed under the Apache license. Activiti runs in any Java application, on a server, on a cluster or in the…
Stars: ✭ 8,227 (+13844.07%)
Mutual labels:  spring
Spring Boot Angular5
This repository has a sample code base for spring boot and angular 5 integration.
Stars: ✭ 49 (-16.95%)
Mutual labels:  spring
Springboard
Spring Boot based production grade starter kit.
Stars: ✭ 59 (+0%)
Mutual labels:  spring
Microservices Springboot
Example of microservices application with Spring Boot, Zuul, Eureka, MongoDB and RabbitMQ.
Stars: ✭ 53 (-10.17%)
Mutual labels:  spring
Geekshop
极客商城 ~ 一个面向开发者的、基于Spring+GraphQL+Angular的、无前端(headless)电商框架
Stars: ✭ 52 (-11.86%)
Mutual labels:  spring

Test Status

sse-eventbus is a Java library that sits on top of Spring's Sever-Sent Event support.
It keeps track of connected clients and broadcasts events to them.

Usage

Setup server

Enable support by adding @EnableSseEventBus to a Spring application.

@SpringBootApplication
@EnableSseEventBus
public class Application {
  ...
}

Create a controller that handles the SSE requests and returns a SseEmitter. Each client has to provide an id that identifies this client. The controller then registers the client in the eventBus with the method registerClient and subscribes it to events with the subscribe method. The SseEventBus class contains a convenient method createSseEmitter that does all of this.

@Controller
public class SseController {
  private final SseEventBus eventBus;
  public SseController(SseEventBus eventBus) {
    this.eventBus = eventBus;
  }

  @GetMapping("/register/{id}")
  public SseEmitter register(@PathVariable("id") String id) {
    SseEmitter emitter = new SseEmitter(180_000L);
    emitter.onTimeout(emitter::complete);
    this.eventBus.registerClient(id, emitter);
    this.eventBus.subscribe(id, SseEvent.DEFAULT_EVENT);
    return emitter;

    //OR
    //return this.eventBus.createSseEmitter(id, SseEvent.DEFAULT_EVENT)
  }
}

Setup client

On the client side an application interacts with the EventSource object. This object is responsible for sending the SSE request to the server and calling listeners the application registered on this object. As mentioned before the client has to send an id that should be unique among all the clients. A simple way is to use libraries like node-uuid that generates UUIDs.

const uuid = uuid();
const eventSource = new EventSource(`/register/${uuid}`);
eventSource.addEventListener('message', response => {
  //handle the response from the server
  //response.data contains the data line 
}, false);

Broadcasting events

To broadcast an event to all connected clients a Spring application can either inject the SseEventBus singleton and call the handleEvent method

@Service
public class DataEmitterService {
  private final SseEventBus eventBus;
  public DataEmitterService(SseEventBus eventBus) {
    this.eventBus = eventBus;
  }

  public void broadcastEvent() {
    this.eventBus.handleEvent(SseEvent.ofData("some useful data"));
  }

}

or use Spring's event infrastructure and publish a SseEvent

@Service
public class DataEmitterService {
  private final ApplicationEventPublisher eventPublisher;
  // OR: private final ApplicationContext ctx;
  // this class implements the ApplicationEventPublisher interface
  public DataEmitterService(ApplicationEventPublisher eventPublisher) {
    this.eventPublisher = eventPublisher;
  }

  public void broadcastEvent() {
    this.eventPublisher.publishEvent(SseEvent.ofData("some useful data"));
  }
}

Maven

The library is hosted on the Central Maven Repository

  <dependency>
    <groupId>ch.rasc</groupId>
    <artifactId>sse-eventbus</artifactId>
    <version>1.1.9</version>
  </dependency>  

Demo

Simple demo application:
https://github.com/ralscha/sse-eventbus-demo

Ionic Demo Chat application:
https://github.com/ralscha/sse-eventbus-demo-chat

More information

Articles about Server-Sent Events

Browser Support

SSE is supported in most browsers. The notable exceptions are the browsers from Microsoft IE and Edge.
http://caniuse.com/#feat=eventsource

Fortunately it is possible to polyfill the SSE support where it's missing.

Changelog

1.1.9 - February 18, 2020

  • Catch and log exceptions in event loop. Prevents the loop to terminate.

1.1.8 - December 21, 2019

  • Resolves Issue #13: Add lifecycle hooks

  • Resolves Issue #12: Hide ImmutableSseEvent completely from public API

1.1.7 - May 24, 2018

  • Resolves Issue #8: Fix handling messages containing a new line character \n

  • Resolves Issue #6: Make members of DefaultSseEventBusConfiguration protected for easier sub classing

1.1.6 - March 21, 2018

  • Change client expiration job to fixed delay and add separate configuration for this delay. By default it is 1 day, you change this value by implementing SseEventBusConfigurer.clientExpirationJobDelay

1.1.5 - January 7, 2018

  • Extract subscription registry code out of the SseEventBus class into the interface SubscriptionRegistry and the class DefaultSubscriptionRegistry. This allows a project to customize the existing implementation or write their own implementation. To override the default implementation add a Spring managed bean of type SubscriptionRegistry to your project.

Example:

@Component
public class CustomSubscriptionRegistry extends DefaultSubscriptionRegistry {

  @Override
  public boolean isClientSubscribedToEvent(String clientId, String eventName) {
    return super.isClientSubscribedToEvent(clientId, eventName)
        || super.isClientSubscribedToEvent(clientId, "*");
  }
}  

1.1.4 - December 15, 2017

  • Resolves Issue #2. Make sure that your project depends on Spring 4.3.13 or newer.

1.1.3 - September 12, 2017

  • Add the following public methods to the SseEventBus class to query events and subscribers.
    • Set getAllClientIds()
    • Set getAllEvents()
    • Map<String, Set> getAllSubscriptions()
    • Set getSubscribers(String event)
    • int countSubscribers(String event)
    • boolean hasSubscribers(String event)

1.1.2 - July 16, 2017

  • Add a workaround for the Microsoft Edge browser where the polyfill no longer work correctly. The createSseEmitter method supports an additional parameter that tells the library to complete (close) the connection after sending a message. This way the system behaves like long polling instead of http streaming.
boolean completeAfterMessage = true;
eventBus.createSseEmitter("client1", 180_000L, true, completeAfterMessage, "event1", "event2");

1.1.1 - July 8, 2017

  • Add support for automatic unregister clients from events during registering. SseEventBus.createSseEmitter supports an additional boolean parameter. If true the method subscribes the client to the provided events and unsubscribes it from all other currently subscribed events.

    eventBus.createSseEmitter("client1", 180_000L, true, "event1", "event2");
    After this call the client is only subscribed to event1 and event2.

    ...later in the application...

    eventBus.createSseEmitter("client1", 180_000L, true, "event1");
    After this call the client is only subscribed to event1. The method automatically unregistered the client from event2.

1.1.0 - April 28, 2017

  • Add support for Jackson JSON View. SseEvent.builder().event("eventName").data(dataObj).jsonView(JsonViews.PUBLIC.class).build()
    To support that the interface ch.rasc.sse.eventbus.DataObjectConverter changed. Instead of the data object the two methods receive the SseEvent object.
    1.0.x: boolean supports(Object object); String convert(Object object);
    1.1.x: boolean supports(SseEvent event); String convert(SseEvent event);
    To get the data object your code can call event.data().

1.0.1 - March 31, 2017

  • Add support for excluding clients with the addExcludeClientId method.
    SseEvent.builder().addExcludeClientId("2")
          .event("eventName")
          .data("payload")
          .build();
    

1.0.0 - November 19, 2016

  • Initial release

License

Code released under the Apache license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].