Socket Holder is a socket management framework. Its core functions include socket management, business subscription, and service cluster broadcast.
- Import Dependencies
<dependency>
<groupId>com.isthisone</groupId>
<artifactId>socket-holder-starter</artifactId>
<version>1.1.0</version>
</dependency>
- Configure websocket information
#spring-boot3
spring:
data:
redis:
host: 127.0.0.1
port: 6379
password: 123456
socket-holder:
port: 8081
path: '/ws'
or
#spring-boot2 or earlier
spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456
socket-holder:
port: 8081
path: '/ws'
- Add
@EnableSocketHolder
annotation
@Configuration
@EnableSocketHolder
public class SocketHolderConfiguration {
}
- Create Websocket processing class
@RequiredArgsConstructor
@Component
@Slf4j
public class MyWebsocketHandler implements WebsocketHandler {
private final StringSubscriberNotify stringSubscriberNotify;
@Override
public void process(HolderChannel channel, String text) {
log.info("id-{},text-{}", channel.getId(), text);
stringSubscriberNotify.subscribe("key", channel);
}
}
- Use client to publish messages
@Component
@RequiredArgsConstructor
public class Tester() {
private final SocketHolderClient socketHolderClient;
public void test() {
socketHolderClient.broadcast("Hello!");
}
}
- Create redis broadcast class.
@RequiredArgsConstructor
@Component
@Slf4j
public class MyRedisBroadcastListener extends RedisBroadcastListener {
private final StringSubscriberNotify stringSubscriberNotify;
@Override
public void listen(String topic, String msg) {
log.info("topic-{},msg-{}", topic, msg);
stringSubscriberNotify.notify("key", msg);
}
}