@@ -80,3 +80,57 @@ This guide will show you how to enable leader election for your application.
80
80
## Using leader election in your application (Server Sent Events API)
81
81
82
82
:construction_worker : Help Wanted! Please contribute with examples on how to use the Server Sent Events API.
83
+
84
+
85
+ === "Kotlin with Spring"
86
+
87
+ WebFlux to create a subscription, and an ApplicationEvent to inform about changes.
88
+
89
+ ```kotlin
90
+ @Service
91
+ class LederUtvelger :ApplicationListener<LeaderChangedEvent> {
92
+
93
+ private val hostname = InetAddress.getLocalHost().hostName
94
+ var erLeder : Boolean = false
95
+
96
+ override fun onApplicationEvent(event: LeaderChangedEvent) {
97
+ erLeder = event.leder == hostname
98
+ }
99
+ }
100
+
101
+
102
+ @Component
103
+ class SSEHandler(builder: Builder, @Value("\${elector.sse.url}") uri: URI, publisher: ApplicationEventPublisher) {
104
+ init {
105
+ builder.build()
106
+ .get()
107
+ .uri(uri)
108
+ .retrieve()
109
+ .bodyToFlux(LederUtvelgerRespons::class.java).subscribe {
110
+ publisher.publishEvent(LeaderChangedEvent(this,it.name))
111
+ }
112
+ }
113
+ data class LederUtvelgerRespons(val name: String, val last_update: LocalDateTime)
114
+ class LeaderChangedEvent(source: Any, val leder: String) : ApplicationEvent(source)
115
+ }
116
+ ```
117
+
118
+
119
+ === "Python with sseclient"
120
+
121
+ Using `sseclient` to subscribe to the leader election events, and passing them to a handler function.
122
+ Probably needs to be run in a separate thread.
123
+
124
+ ```python
125
+ import os
126
+ from typing import Callable
127
+
128
+ from sseclient import SSEClient
129
+
130
+
131
+ def subscribe_leader_election(handler: Callable[[str], None]):
132
+ url = os.getenv("ELECTOR_SSE_URL")
133
+ messages = SSEClient(url)
134
+ for msg in messages:
135
+ handler(msg)
136
+ ```
0 commit comments