SprinngBoot下集成webSock的几种方式
基于kafka配置推送
package cn. microvideo. flowac. sys. util ;
import cn. microvideo. flowac. sys. entity. LocalSysMsgForWSBean ;
import cn. microvideo. flowac. sys. entity. WSMsgModuleEnum ;
import org. springframework. beans. factory. annotation. Value ;
import org. springframework. kafka. core. KafkaTemplate ;
import org. springframework. stereotype. Component ;
import javax. annotation. PostConstruct ;
import javax. annotation. Resource ;
@Component
public class WebSocketUtil {
private static WebSocketUtil instance;
@Resource ( name = "kafkaOneTemplate" )
private KafkaTemplate < String , Object > kafkaTemplate;
@Value ( "${localSysMessageForWSTopic}" )
private String localSysMessageForWSTopic;
@PostConstruct
public void init ( ) {
instance = this ;
}
public static void sendForWS ( Object message, WSMsgModuleEnum moduleEnum) {
LocalSysMsgForWSBean bean = createBean ( message, moduleEnum, 0 ) ;
instance. kafkaTemplate. send ( instance. localSysMessageForWSTopic, GsonUtil . toJson ( bean) ) ;
}
public static void sendForWSByUnit ( Object message, WSMsgModuleEnum moduleEnum, String unitCode) {
LocalSysMsgForWSBean bean = createBean ( message, moduleEnum, 1 ) ;
bean. setUnitCode ( unitCode) ;
instance. kafkaTemplate. send ( instance. localSysMessageForWSTopic, GsonUtil . toJson ( bean) ) ;
}
public static void sendForWSByUser ( Object message, WSMsgModuleEnum moduleEnum, String userId) {
LocalSysMsgForWSBean bean = createBean ( message, moduleEnum, 2 ) ;
bean. setUserId ( userId) ;
instance. kafkaTemplate. send ( instance. localSysMessageForWSTopic, GsonUtil . toJson ( bean) ) ;
}
private static LocalSysMsgForWSBean createBean ( Object message, WSMsgModuleEnum moduleEnum, Integer sendType) {
LocalSysMsgForWSBean bean = new LocalSysMsgForWSBean ( ) ;
bean. setModule ( moduleEnum. getModule ( ) ) ;
bean. setMessageType ( moduleEnum. getMessageType ( ) ) ;
bean. setSendType ( sendType) ;
bean. setMessage ( message) ;
return bean;
}
}
基于session配置推送
package com. microvideo. ewcp. configration ;
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 ( ) ;
}
}
package com. microvideo. ewcp. configration ;
import java. io. IOException ;
import java. util. concurrent. CopyOnWriteArraySet ;
import javax. websocket. OnClose ;
import javax. websocket. OnError ;
import javax. websocket. OnMessage ;
import javax. websocket. OnOpen ;
import javax. websocket. Session ;
import javax. websocket. server. PathParam ;
import javax. websocket. server. ServerEndpoint ;
import org. springframework. stereotype. Component ;
@Component
@ServerEndpoint ( "/websocket/{sid}/{rid}" )
public class WebSocketServer {
private static int onlineCount = 0 ;
private static CopyOnWriteArraySet < WebSocketServer > webSocketSet = new CopyOnWriteArraySet < WebSocketServer > ( ) ;
private Session session;
private String sid= "" ;
public static final String event = "fk_centerid" ;
@OnOpen
public void onOpen ( Session session, @PathParam ( "sid" ) String sid, @PathParam ( "rid" ) String rid) {
this . session = session;
webSocketSet. add ( this ) ;
addOnlineCount ( ) ;
this . sid= sid;
}
@OnClose
public void onClose ( @PathParam ( "rid" ) String rid) {
webSocketSet. remove ( this ) ;
subOnlineCount ( ) ;
}
@OnMessage
public void onMessage ( String message, Session session) {
for ( WebSocketServer item : webSocketSet) {
try {
item. sendMessage ( message) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
@OnError
public void onError ( Session session, Throwable error) {
error. printStackTrace ( ) ;
}
public void sendMessage ( String message) throws IOException {
this . session. getBasicRemote ( ) . sendText ( message) ;
}
public static void sendInfo ( String message, @PathParam ( "sid" ) String sid) throws IOException {
for ( WebSocketServer item : webSocketSet) {
try {
if ( sid== null ) {
item. sendMessage ( message) ;
} else if ( item. sid. equals ( sid) ) {
item. sendMessage ( message) ;
}
} catch ( IOException e) {
continue ;
}
}
}
public static synchronized int getOnlineCount ( ) {
return onlineCount;
}
public static synchronized void addOnlineCount ( ) {
WebSocketServer . onlineCount++ ;
}
public static synchronized void subOnlineCount ( ) {
WebSocketServer . onlineCount-- ;
}
}
基于redis配置推送
package cn. microvideo. flowac. services. util ;
import cn. microvideo. flowac. services. common. util. MicrovideoCommRedisRepository ;
import cn. microvideo. flowac. services. wsmsg. entity. WsMsgDto ;
import cn. microvideo. flowac. services. wsmsg. entity. WsMsgModuleEnum ;
import cn. microvideo. flowac. services. wsmsg. entity. WsProjGroupEnum ;
import cn. microvideo. flowac. services. wsmsg. entity. WsReceiveDto ;
import org. springframework. stereotype. Component ;
import javax. annotation. PostConstruct ;
import javax. annotation. Resource ;
import java. util. concurrent. TimeUnit ;
@Component
public class WebSocketUtil {
private static WebSocketUtil instance;
@Resource
private MicrovideoCommRedisRepository redisUtil;
@PostConstruct
public void init ( ) {
instance = this ;
}
public static void sendToAll ( WsProjGroupEnum projGroupEnum, WsMsgModuleEnum wsMsgModule, Object content) {
WsMsgDto msgDto = new WsMsgDto ( ) ;
msgDto. setWsMsgModuleEnum ( wsMsgModule) ;
msgDto. setContext ( content) ;
WsReceiveDto receiveDto = new WsReceiveDto ( ) ;
receiveDto. setReceiveBodyType ( 0 ) ;
receiveDto. setMsg ( msgDto) ;
instance. redisUtil. strLeftPush ( projGroupEnum. getProjGroup ( ) , receiveDto, TimeUnit . MINUTES. toMillis ( 5 ) ) ;
}
public static void sendToDept ( WsProjGroupEnum projGroupEnum, WsMsgModuleEnum wsMsgModule, String deptId,
Object content) {
WsMsgDto msgDto = new WsMsgDto ( ) ;
msgDto. setWsMsgModuleEnum ( wsMsgModule) ;
msgDto. setContext ( content) ;
WsReceiveDto receiveDto = new WsReceiveDto ( ) ;
receiveDto. setReceiveBodyType ( 1 ) ;
receiveDto. setReceiveBodyCode ( deptId) ;
receiveDto. setMsg ( msgDto) ;
instance. redisUtil. strLeftPush ( projGroupEnum. getProjGroup ( ) , receiveDto, TimeUnit . MINUTES. toMillis ( 5 ) ) ;
}
public static void sendToUser ( WsProjGroupEnum projGroupEnum, WsMsgModuleEnum wsMsgModule, String userId,
Object content) {
WsMsgDto msgDto = new WsMsgDto ( ) ;
msgDto. setWsMsgModuleEnum ( wsMsgModule) ;
msgDto. setContext ( content) ;
WsReceiveDto receiveDto = new WsReceiveDto ( ) ;
receiveDto. setReceiveBodyType ( 2 ) ;
receiveDto. setReceiveBodyCode ( userId) ;
receiveDto. setMsg ( msgDto) ;
instance. redisUtil. strLeftPush ( projGroupEnum. getProjGroup ( ) , receiveDto, TimeUnit . MINUTES. toMillis ( 5 ) ) ;
}
}
package cn. microvideo. flowac. equipment. 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 ( ) ;
}
}
package cn. microvideo. flowac. equipment. websocket ;
import cn. microvideo. flowac. services. common. util. MicrovideoCommRedisRepository ;
import cn. microvideo. flowac. services. wsmsg. entity. WsMsgDto ;
import cn. microvideo. flowac. services. wsmsg. entity. WsProjGroupEnum ;
import cn. microvideo. flowac. services. wsmsg. entity. WsReceiveDto ;
import cn. microvideo. framework. core. util. json. MicrovideoJsonUtil ;
import lombok. extern. slf4j. Slf4j ;
import org. apache. commons. lang3. StringUtils ;
import org. springframework. stereotype. Component ;
import javax. annotation. PostConstruct ;
import javax. annotation. Resource ;
@Slf4j
@Component
public class WebSocketSendHandle {
@Resource
private MicrovideoCommRedisRepository redisUtil;
@PostConstruct
public void init ( ) {
try {
new Thread ( new WebSocketSendHandleC ( ) ) . start ( ) ;
} catch ( Exception e) {
log. error ( "" , e) ;
}
}
private class WebSocketSendHandleC implements Runnable {
@Override
public void run ( ) {
log. info ( "【WebSocketSendHandle】已初始化完成..." ) ;
while ( true ) {
try {
Thread . sleep ( 50 ) ;
String msgStr = redisUtil. strRigthPop ( WsProjGroupEnum . WS_EQUIP_PROJ_GROUP. getProjGroup ( ) ) ;
if ( StringUtils . isEmpty ( msgStr) ) {
continue ;
}
WsReceiveDto wsReceiveDto = MicrovideoJsonUtil . parseObject ( msgStr, WsReceiveDto . class ) ;
WsMsgDto wsMsgDto = wsReceiveDto. getMsg ( ) ;
String wsMsgStr = MicrovideoJsonUtil . toJSONString ( wsMsgDto) ;
Integer receiveBodyType = wsReceiveDto. getReceiveBodyType ( ) ;
String receiveBodyCode = wsReceiveDto. getReceiveBodyCode ( ) ;
if ( receiveBodyType == 0 ) {
WebSocketServer . sendMessageToAll ( wsMsgStr) ;
} else if ( receiveBodyType == 1 && ! StringUtils . isEmpty ( receiveBodyCode) ) {
WebSocketServer . sendMessageToDept ( wsMsgStr, receiveBodyCode) ;
} else if ( receiveBodyType == 2 && ! StringUtils . isEmpty ( receiveBodyCode) ) {
WebSocketServer . sendMessageToUser ( wsMsgStr, receiveBodyCode) ;
}
} catch ( Exception e) {
log. error ( "" , e) ;
}
}
}
}
}
package cn. microvideo. flowac. equipment. websocket ;
import lombok. extern. slf4j. Slf4j ;
import org. springframework. stereotype. Component ;
import javax. websocket. OnClose ;
import javax. websocket. OnError ;
import javax. websocket. OnMessage ;
import javax. websocket. OnOpen ;
import javax. websocket. Session ;
import javax. websocket. server. PathParam ;
import javax. websocket. server. ServerEndpoint ;
import java. io. IOException ;
import java. util. concurrent. CopyOnWriteArraySet ;
@Component
@ServerEndpoint ( "/websocket/{deptId}/{userId}" )
@Slf4j
public class WebSocketServer {
private static final CopyOnWriteArraySet < WebSocketServer > WS_CONN_SET = new CopyOnWriteArraySet < > ( ) ;
private Session session;
private String userId = "" ;
private String deptId = "" ;
@OnOpen
public void onOpen ( Session session, @PathParam ( "deptId" ) String deptId, @PathParam ( "userId" ) String userId) {
this . session = session;
this . deptId = deptId;
this . userId = userId;
WS_CONN_SET. add ( this ) ;
log. info ( ">>>WEBSOCKET<<< userId={},sessionId={}, open connection" , userId, session. getId ( ) ) ;
}
@OnClose
public void onClose ( ) {
log. info ( ">>>WEBSOCKET<<< userId={},sessionId={}, close connection" , userId, session. getId ( ) ) ;
}
@OnMessage
public String onMessage ( String message, Session session) {
log. info ( ">>>WEBSOCKET<<< get userId={} sessionId={} message, context={}" , userId, session. getId ( ) , message) ;
return "receive message success!!" ;
}
public static void sendMessageToAll ( String message) {
log. info ( "【WS_SEND TO ALL】content={}" , message) ;
for ( WebSocketServer server : WS_CONN_SET) {
try {
server. sendMessage ( message) ;
} catch ( IOException e) {
log. error ( "" , e) ;
}
}
}
public static void sendMessageToDept ( String message, String deptId) {
log. info ( "【WS_SEND TO DRPT】deptId={},content={}" , deptId, message) ;
for ( WebSocketServer server : WS_CONN_SET) {
try {
if ( ! server. deptId. equals ( deptId) ) {
continue ;
}
server. sendMessage ( message) ;
} catch ( IOException e) {
log. error ( "" , e) ;
}
}
}
public static void sendMessageToUser ( String message, String userId) {
log. info ( "【WS_SEND TO USER】userId={},content={}" , userId, message) ;
for ( WebSocketServer server : WS_CONN_SET) {
try {
if ( ! server. userId. equals ( userId) ) {
continue ;
}
server. sendMessage ( message) ;
} catch ( IOException e) {
log. error ( "" , e) ;
}
}
}
public void sendMessage ( String message) throws IOException {
if ( session. isOpen ( ) ) {
this . session. getBasicRemote ( ) . sendText ( message) ;
}
}
@OnError
public void onError ( Session session, Throwable error) {
log. error ( ">>>WEBSOCKET<<< userId={},sessionId={}, connection error, exception={}" , userId, session. getId ( ) ,
error) ;
}
}