Skip to content

Commit e355e2c

Browse files
authored
[Optimization-4474][admin] Optimize websocket in login page (#4475)
1 parent db80b96 commit e355e2c

3 files changed

Lines changed: 54 additions & 10 deletions

File tree

dinky-admin/src/main/java/org/dinky/ws/GlobalWebSocket.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,10 @@ public void sendTopic(GlobalWebSocketTopic topic, Map<String, ?> paramsAndData)
174174
Map<GlobalWebSocketTopic, Set<String>> topics = requestDTO.getTopics();
175175
if ((topics.containsKey(topic) && topics.get(topic).contains(params))
176176
|| params.equals(WsMessageEventHandler.NONE_PARAMS)) {
177-
tempMap.computeIfAbsent(session, k -> topics.get(topic)).add(params);
177+
Set<String> stringSet = tempMap.computeIfAbsent(session, k -> topics.get(topic));
178+
if (stringSet != null) {
179+
stringSet.add(params);
180+
}
178181
}
179182
}));
180183

dinky-web/src/models/UseWebSocketModel.tsx

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { ErrorMessage } from '@/utils/messages';
2222
import { v4 as uuidv4 } from 'uuid';
2323
import { TOKEN_KEY } from '@/services/constants';
2424
import { TOKEN_MODEL_ASYNC } from '@/pages/AuthCenter/Token/component/model';
25+
import { useModel } from '@umijs/max';
2526

2627
export type WsData = {
2728
topic: string;
@@ -49,18 +50,34 @@ export type WsState = {
4950
wsUrl: string;
5051
};
5152

52-
export default () => {
53+
export default (): {
54+
subscribeTopic: (topic: Topic, params: string[], onMessage: (data: WsData) => void) => () => void;
55+
reconnect: () => void;
56+
wsState: WsState;
57+
} => {
5358
const subscriberRef = useRef<SubscriberData[]>([]);
5459
const lastPongTimeRef = useRef<number>(new Date().getTime());
60+
const { initialState }: { initialState: any } = useModel('@@initialState');
5561

5662
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
5763
const token = JSON.parse(localStorage.getItem(TOKEN_KEY) ?? '{}')?.tokenValue;
5864
const wsUrl = `${protocol}://${window.location.hostname}:${window.location.port}/api/ws/global/${token}`;
59-
const [wsState, setWsState] = useState<WsState>({ wsOnReady: true, wsUrl });
65+
66+
// Check if the user is logged in. Establish a WebSocket connection only when the user is in a logged in state.
67+
const isLoggedIn: boolean = !!(initialState?.currentUser && token);
68+
const [wsState, setWsState] = useState<WsState>({
69+
wsOnReady: isLoggedIn,
70+
wsUrl: isLoggedIn ? wsUrl : ''
71+
});
6072

6173
const ws = useRef<WebSocket>();
6274

6375
const reconnect = () => {
76+
// Only attempt to reconnect when in a logged - in state.
77+
if (!isLoggedIn) {
78+
return;
79+
}
80+
6481
if (ws.current && ws.current.readyState === WebSocket.OPEN) {
6582
ws.current.close();
6683
}
@@ -76,6 +93,11 @@ export default () => {
7693
};
7794

7895
const subscribe = () => {
96+
// Only attempt to subscribe when you are logged in.
97+
if (!isLoggedIn) {
98+
return;
99+
}
100+
79101
const topics: Record<string, string[]> = {};
80102
subscriberRef.current.forEach((sub) => {
81103
if (!topics[sub.topic]) {
@@ -114,8 +136,13 @@ export default () => {
114136
};
115137

116138
useEffect(() => {
139+
// Only initialize the WebSocket connection when logged in.
140+
if (!isLoggedIn) {
141+
return;
142+
}
143+
117144
receiveMessage();
118-
setInterval(() => {
145+
const interval = setInterval(() => {
119146
if (!ws.current || ws.current.readyState != WebSocket.OPEN) {
120147
reconnect();
121148
} else {
@@ -127,16 +154,27 @@ export default () => {
127154
}
128155
}
129156
}, 2000);
130-
}, []);
157+
158+
return () => {
159+
clearInterval(interval);
160+
};
161+
}, [isLoggedIn]);
131162

132163
const subscribeTopic = (topic: Topic, params: string[], onMessage: (data: WsData) => void) => {
133164
const sub: SubscriberData = { topic: topic, call: onMessage, params: params, key: uuidv4() };
134165
subscriberRef.current.push(sub);
135-
subscribe();
166+
167+
// Only attempt to subscribe when in the logged in state.
168+
if (isLoggedIn) {
169+
subscribe();
170+
}
171+
136172
return () => {
137-
//组件卸载回调方法,取消订阅此topic
173+
// Callback method for component unmounting. Unsubscribe from this topic.
138174
subscriberRef.current = subscriberRef.current.filter((item) => item.key !== sub.key);
139-
subscribe();
175+
if (isLoggedIn) {
176+
subscribe();
177+
}
140178
};
141179
};
142180

dinky-web/src/pages/Other/Login/index.tsx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ const Login: React.FC = () => {
6161
}
6262
};
6363

64+
useEffect(() => {
65+
initSomeThing();
66+
}, []);
67+
6468
/**
6569
* When the token is expired, redirect to login
6670
*/
@@ -180,8 +184,7 @@ const Login: React.FC = () => {
180184
await handleChooseTenant(result);
181185
handleTenantVisible(false);
182186
};
183-
// 进入登录页初始化一些东西
184-
initSomeThing();
187+
185188
return (
186189
<div className={containerClassName}>
187190
<HelmetTitle />

0 commit comments

Comments
 (0)