数据流转
# 背景
当后台服务器判断出现了报警信息,需要主动推送到客户端【web、小程序】,然后客户端接收到通知之后,向服务器端进行查询
# 技术选型
Netty
+webSocket
+protobuf
- Netty:作为高性能网络框架,一般将用于网络对接时框架首选
- websocket:服务器端向客户端通信,目前浏览器方案【PC、小程序】的不二之选
- protobuf:Google开源的传输协议,可降低传输带宽,相比使用字符串传输,也可起到数据加密的作用
- Nginx:Nginx代理websocket长链接 (opens new window)
# 功能设计
- 客户端通过
websocket
方式连接服务器端,主动发送token进行校验。目前初步校验:当前用户是否是成功登录用户 - 推送执行的场景
- 报警产生时
- 报警状态变化【未处理】
- 推送对象
- imei — group — username,获取设备报警需要推送的用户
- client connect server,将经过校验的用户放入缓存
- 推送流程
- 设备报警状态变更,判断该
设备
需要推送给那些用户
- 判断通过websocket
连接的用户
有多少,进行推送
- 设备报警状态变更,判断该
# 功能实现
- 通过设备查询该设备所属分组 groupId
- 判断当前系统有多少用户已经连接 username — tokenId
- 通过
admin:user_groupIds
判断连接的用户,有多少需要推送【groupId 是否包含】
# Nginx配置websocket代理
- 编辑
nginx.conf
,在http区域内一定要添加下面配置:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
1
2
3
4
2
3
4
map指令的作用: 该作用主要是根据客户端请求中
$http_upgrade
的值,来构造改变$connection_upgrade
的值,即根据变量$http_upgrade
的值创建的变量$connection_upgrade
,创建的规则就是{}
里面的东西。其中的规则没有做匹配,因此使用默认的,即$connection_upgrade
的值会一直是upgrade
。然后果$http_upgrade
为空字符串的话,那值会是close
。编辑vhosts下虚拟主机的配置文件,在location匹配配置中添加如下内容:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
1
2
3
2
3
示例如下:
upstream socket.kevin.com {
hash $remote_addr consistent;
server 192.168.1.168:9088;
}
location / {
proxy_pass http://socket.kevin.com/;
proxy_set_header Host $host:$server_port;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- 可能会出现跨域问题,server区块填写以下跨域配置即可
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') { return 204; }
1
2
3
4
2
3
4
上次更新: 2023/03/25, 13:26:36