springboot 优雅使用函数式编程处理 websocket @OnMessage 消息

本文主要是介绍springboot 优雅使用函数式编程处理 websocket @OnMessage 消息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

背景

现在大多业务功能使用 socket.io实现长连接,但是部分第三方设备对接 只支持基础的websocket。
spring中使用基础的websocket, @OnMessage 收到消息,对消息的处理,if else 将会繁琐,难以维护。

本文仅介绍了如何使用enum枚举、java.util.function jdk8 函数式接口,实现消息的处理。

websocket 定义JSON 数据交换格式

本文使用的 示例格式:

//连接成功
{"cmd":"connect","sn":"A7888","data":{...}}
//设置人员
{"cmd":"setUser","data":{"userId":"1"}}
//控制设备 --多层级 的格式,第二层里面解析 仍可按照同样的方式来处理
{"cmd":"to_client","data":{"type":"openDoor","value":"ON"}}

springboot 集成websocket

pom.xml 依赖
        <!-- spring websocket--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><!-- spring websocket启动异常、排除spring-boot-starter-tomcat--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId></exclusion></exclusions></dependency>       
定义WebSocketConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}
定义 @ServerEndpoint
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.OnOpen;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;/*** 定义websocket端点*/
@Slf4j
@ServerEndpoint(value = "/socket/device")
@Component
public class DeviceServerEndpoint {/*** 记录当前在线连接数*/private static AtomicInteger onlineCount = new AtomicInteger(0);/*** 连接的对象*/public static final Map<String, Session> clientMap = new ConcurrentHashMap<>();/*** 收到客户端消息** @param message 客户端发送过来的消息* @throws*/@OnMessagepublic void onMessage(String message, Session session) {try {DeviceMsg deviceMsg = JSON.parseObject(message, DeviceMsg.class);if (deviceMsg != null && deviceMsg.getCmd() != null) {// jdk8 函数式处理消息deviceMsg.getCmd().consumer.accept(session, message);} else {log.info("无法自动处理,客户端消息:{}", message);}} catch (Exception e) {log.error("消息处理失败", session.getId(), message);e.printStackTrace();}}/*** 连接建立成功*/@OnOpenpublic void onOpen(Session session) {onlineCount.incrementAndGet(); // 在线数加1log.info("有新连接加入:{},当前在线数为:{}", session.getId(), onlineCount.get());}/*** 连接关闭*/@OnClosepublic void onClose(Session session) {onlineCount.decrementAndGet(); // 在线数减1log.info("有一连接关闭:{},当前在线数为:{}", session.getId(), onlineCount.get());}@OnErrorpublic void onError(Session session, Throwable error) {onlineCount.decrementAndGet(); // 在线数减1error.printStackTrace();}/*** 测试 控制开锁*/public static void openDoor() {//所有客户端发送消息clientMap.forEach((id, session) -> {session.getBasicRemote().sendText("ON");}}
deviceMsg实体类
import lombok.Data;
import java.io.Serializable;@Data
public class DeviceMsg implements Serializable {/*** 指令*/Cmd cmd;/*** 数据块*/JSONObject data;
}
Cmd 核心消息处理 枚举类

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import javax.websocket.Session;
import java.util.function.BiConsumer;@Getter
@Slf4j
@AllArgsConstructor
public enum Cmd {connect("设备连接成功", (Session session, String msg) -> {//设备端连接成功,发送设置端消息,将Session记录起来DeviceServerEndpoint.clientMap.put(session.getId(), session);}),ping("设备心跳", (Session session, String msg) -> {session.getBasicRemote().sendText("pong");}),setUser("配置用户", (Session session, String msg) -> {//拿到msg 转换对象或者其他操作session.getBasicRemote().sendText("ok");}),to_client("客户端消息", (Session session, String msg) -> {		try {String string = JSON.parseObject(msg).getJSONObject("data").getString("type");Client clientCmd = Client.valueOf(string);clientCmd.consumer.accept(session, msg);} catch (Exception e) {log.info("to_client客户端消息,无法自动处理:{}", msg);}});/*** 描述*/String desc;/*** 处理*/BiConsumer<Session, String> consumer;
}
Client 消息处理枚举类

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;import javax.websocket.Session;
import java.util.function.BiConsumer;@Getter
@Slf4j
@AllArgsConstructor
public enum Client{openDoor("客户端控制", (Session session, String msg) -> {//测试 连接成功 直接 开门DeviceServerEndpoint.openDoor();}),otherCmd("其他指令", (Session session, String msg) -> {session.getBasicRemote().sendText("ok");});/*** 描述*/String desc;/*** 处理*/BiConsumer<Session, String> consumer;
}

JDK8常用函数式编程接口介绍:

  • Function<T, R>:接受一个类型为 T 的参数,返回类型为 R 的结果。常用方法包括 apply(T t)。
  • Predicate:接受一个类型为 T 的参数,返回一个布尔值。常用方法包括 test(T t)。
  • Consumer:接受一个类型为 T 的参数,没有返回值。常用方法包括 accept(T t)。
  • Supplier:不接受任何参数,返回一个类型为 T 的结果。常用方法包括 get()。
  • UnaryOperator:继承自 Function<T, R>,接受一个类型为 T 的参数,返回类型也为 T 的结果。常用方法包括 apply(T t)。
  • BinaryOperator:继承自 BiFunction<T, U, R>,接受两个类型为 T 的参数,返回类型也为 T 的结果。常用方法包括 apply(T t1, T t2)。
  • BiFunction<T, U, R>:接受两个参数,一个类型为 T,一个类型为 U,返回类型为 R 的结果。常用方法包括 apply(T t, U u)。
  • BiPredicate<T, U>:接受两个参数,一个类型为 T,一个类型为 U,返回一个布尔值。常用方法包括 test(T t, U u)。
  • BiConsumer<T, U> :用于接受两个参数,一个类型为 T,一个类型为 U,并且没有返回值。

函数式编程接口的引入,使得在 Java 中能够更方便地实现函数式编程的特性,如Lambda表达式和方法引用。它们可以用于各种场景,例如集合的处理、条件判断、函数的组合等。通过使用这些接口,可以编写更简洁、可读性更高的代码。

附:
WebSocket介绍

这篇关于springboot 优雅使用函数式编程处理 websocket @OnMessage 消息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/649514

相关文章

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解