maven依赖
springboot
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
import xxx.service.CacheService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; /*** * 查询有多少空闲的worker * @author */ @ClientEndpoint @Slf4j @Component public class StatusSocketClient { private Session session; @Value("${ws.asr.status}") String statUrl; @Autowired CacheService cacheService; WebSocketContainer container; @PostConstruct public void init() throws URISyntaxException, IOException, DeploymentException { container = ContainerProvider.getWebSocketContainer(); container.connectToServer(this, new URI(statUrl)); } @PreDestroy public void destroy() throws IOException { //session.getAsyncRemote().sendText("EOS"); if(session!= null) { if(session.isOpen()) { session.close(); } } } @OnOpen public void open(Session session){ log.info("Connected to Real-Time ASR Server Status Socket..."); this.session = session; } @OnMessage public void onMessage(String json){ log.info("Get a status message : " + json); cacheService.setCacheValue("asr.server.status",json); } @OnClose public void onClose(){ log.info("Websocket closed"); } @OnError public void onError(Session session, Throwable t) { t.printStackTrace(); } public void send(String message){ this.session.getAsyncRemote().sendText(message); } public void close() throws IOException { if(this.session.isOpen()){ this.session.close(); } } }
ws.asr.status:ws://172.16.1.238:8888/client/ws/status
他会从这个地址接收服务器状态信息,并且存redis储缓存