1,添加maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
</exclusions>
</dependency>
2,websocket配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig{
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3,socket代码
import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value = "/loginWebSocket/{key}")
public class LoginWebSocket {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private static Map<String, LoginWebSocket> clients = new ConcurrentHashMap<String, LoginWebSocket>();
private Session session;
public String key;
@OnOpen
public void onOpen(@PathParam("key") String key, Session session) {
this.key = key;
this.session = session;
clients.put(key, this);
System.out.println("loginWebSocket key======================="+key);
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("Socket服务端发生了错误" + error.getMessage());
logger.info("Socket服务端发生了错误" + error.getMessage());
}
@OnClose
public void onClose() {
clients.remove(key);
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("loginWebSocket onMessage=========================="+message);
}
public void Notice(String cookie) {
clients.get(key).session.getAsyncRemote().sendText(cookie);
}
public void Notice(SocketResult socketResult) {
System.out.println("loginsocket Notice key====================="+key);
clients.get(key).session.getAsyncRemote().sendText(JSONArray.toJSONString(socketResult));
}
}
4,网关配置webSocket
spring:
cloud:
gateway:
routes:
- id: http1
uri: "http://127.0.0.1:8081" #http转发配置,直接使用http地址使用方式1
#url: "lb://serviceName" #http转发配置,通过nacos注册中心调用serviceName使用方式2
predicates:
- Path=