package com.zhujizheng.IHome.websocket.Net.Base; import com.zhujizheng.IHome.util.ApplicationContextUtils; import com.zhujizheng.IHome.util.response.StringUtils; import com.zhujizheng.IHome.websocket.Net.exception.NetException; import com.zhujizheng.IHome.websocket.response.NetResultGenerator; import com.zhujizheng.IHome.websocket.server.WebSocketServer; import lombok.extern.slf4j.Slf4j; import net.sf.json.JSONObject; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; @Slf4j public class NetProtocolBase { private static final int NET_ERROR_INT = -100; public static void dealWithData(String message, String sid) { if (null == sid) { log.error("sid为空"); return; } // 下面是把拿到的json字符串转成 json对象 JSONObject jsStr = JSONObject.fromObject(message); String protocolName = jsStr.getString("protocolName"); if (protocolName == null) { log.error("收到的消息没有协议号"); return; } String dataString = jsStr.getString("data"); if (dataString == null) { log.error("收到的数据为空"); return; } // 这一步强转成NetProtocolBase,实际执行的时候还是子类实例对象 String lowerCaseFirstOne = StringUtils.toLowerCaseFirstOne(protocolName); NetProtocolBase base = (NetProtocolBase) ApplicationContextUtils.getContext().getBean(lowerCaseFirstOne); if (null == base) { log.error("收到未定义的协议号"); return; } JSONObject json = JSONObject.fromObject(dataString); log.info("收到消息,sid = " + sid + ", json:" + json); base.dealWithJSONAndSid(json, sid); } // 子类重写 public void dealWithJSONAndSid(JSONObject json, String sid) { } // 返回服务器异常 public void sendServerError(String sid) { this.sendObject(NET_ERROR_INT, sid); } public Boolean sendObject(Object obj, String sid) { // 获取当前子类的类名 String className = this.getClass().getSimpleName(); String lowerCaseFirstOne = StringUtils.toLowerCaseFirstOne(className); NetProtocolBase base = (NetProtocolBase) ApplicationContextUtils.getContext().getBean(lowerCaseFirstOne); // className 也是协议号 String string = NetResultGenerator.genResult(obj, className); return base.sendStringWithSidAndRetryable(string, sid); } @Retryable(value = NetException.class, maxAttempts = 5, backoff = @Backoff(value = 3000, multiplier = 1.5)) public Boolean sendStringWithSidAndRetryable(String dataString, String sid) { log.info("发送数据:" + dataString + "sid = " + sid); return WebSocketServer.sendString(dataString, sid); } }