netty-websocket-spring-boot-starter是一個基於netty的websocket服務端,目前筆者使用的版本依托於Springboot。
官方網址https://github.com/YeautyYE/netty-websocket-spring-boot-starter
本文將幫你解決以下問題:
ws://www.aaa.com/api/asr
ws://www.aaa.com/api/tts
共用一個JVM,減少不必要的內存開銷。
當然示例很簡單,在官方文檔也有說。
以下是代碼
application.yml
spring: netty-websocket: host: 0.0.0.0 port: 80 #默認80可不填寫
注意事項:prefix = "spring.netty-websocket"需要和配置文件里面的路徑一直,這個屬性文件查找的前綴,會有一些默認的值。比如
path="/",port=80,如果是這些值,在配置文件里可以不寫,只寫host
RealTimeTTSEndpoint.java負責處理 /api/tts相關業務
import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import org.yeauty.annotation.OnClose; import org.yeauty.annotation.OnError; import org.yeauty.annotation.OnMessage; import org.yeauty.annotation.OnOpen; import org.yeauty.annotation.ServerEndpoint; import org.yeauty.pojo.ParameterMap; import org.yeauty.pojo.Session; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.net.URI; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @ServerEndpoint(prefix = "spring.netty-websocket",path = "/api/tts") @Component @Slf4j public class RealTimeTTSEndpoint { }
RealTimeASREndpoint.java負責處理/api/asr相關業務
import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.timeout.IdleStateEvent; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.yeauty.annotation.OnBinary; import org.yeauty.annotation.OnClose; import org.yeauty.annotation.OnError; import org.yeauty.annotation.OnEvent; import org.yeauty.annotation.OnMessage; import org.yeauty.annotation.OnOpen; import org.yeauty.annotation.ServerEndpoint; import org.yeauty.pojo.Session; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @ServerEndpoint(prefix = "spring.netty-websocket",path = "/api/asr") @Component @Slf4j public class RealTimeASREndpoint { }