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储缓存
本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。