背景: 這個websocket 因為使用的地方不多,並沒有獨立出一個項目,是集成在已有的服務中。
1: gateway 配置
- id: service-test
uri: lb:ws://service-test
predicates:
- Path=/ws/**
filters:
- StripPrefix=1
注釋:
lb:ws: 表示要轉發websocket協議
Path=/ws/** 表示請求path 是 ip:port/ws/** 請求,會轉發到 id 為 service-test 的服務
StripPrefix=1 過濾掉/ws的路徑
ok 啟動 gateway , 我的gateway 端口是 7002
2: service-test 服務配置
pom.xml 添加 websocket的配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置代碼(這里只展示連接的代碼,其他的可以看下文檔)
@ServerEndpoint("/webSocket")
@Component
public class WebSocketStart {
private static Map<String, List<SessionInfo>> sessionMap = Maps.newConcurrentMap();
/**
* 連接
*/
@OnOpen
public void connected(Session session) {
session.getAsyncRemote().sendText("小伙子登陸成功!!!");
// cacheSession(session);
}
}
ok 啟動 service-test , 我的 service-test 端口是 8091
先測試下 service-test 是否能連接成功。
再來測試下 gateway