Websocket消息推送——SpringCloud(Zuul)

Springboot+zuul集成webSocket,实现通信
由于zuul对websocket的支持不够友好,也就是说websocket的请求无法穿透zuul。
我们可以通过在网关搭建websocket来实现消息推送功能。子模块通过OpenFeign来访问网关模块,网关模块发送websocket消息,实现消息推送。

子模块

@RestController
@RequestMapping("/api/msg")
public class MessageController  extends CommonController {
    @Autowired(required = false)
    private MsgClient msgClient;

    @ResponseBody
    @RequestMapping(value = "/sendMsg/{toUserId}",method = {RequestMethod.POST})
    public R sendMsg(@RequestBody Message msg, @PathVariable("toUserId") String toUserId){
    		/
            msgClient.pushToWeb(msg,toUserId);
            //
}
@FeignClient(
    name = "gateway",
    fallback = MsgClient.MsgClientFallback.class,
    path = "/msg"
)
public interface MsgClient {

    @ResponseBody
    @RequestMapping({"/push/entity/{toUserId}"})
    R pushToWeb(@RequestBody Message var1, @PathVariable("toUserId") String var2);


    @Component
    public static class MsgClientFallback implements MsgClient {
        private static final Logger log = LoggerFactory.getLogger(MsgClient.MsgClientFallback.class);

        public MsgClientFallback() {
        }

        public R pushToWeb(Message message, String toUserId) {
            return null;
        }
    }
}

Zuul模块

网关发送消息前保存消息依旧通过openfign调用原来模块(sysMessageClient.saveMsg(message);),
然后再用websoket推送消息(WebSocketServer.sendInfo(JSON.toJSONString(JSON.toJSON(message)), toUserId,“”,“”);)。

@Slf4j
@Api(value = "系统消息API",tags = "MSG")
@RestController
@RequestMapping("/msg")
public class MessageController {
    @Autowired
    private SysMessageClient sysMessageClient;

    @ResponseBody
    @RequestMapping("/push/entity/{toUserId}")
    public R pushToWeb(@RequestBody Message message, @PathVariable("toUserId") String toUserId) {
        try {
            R r = sysMessageClient.saveMsg(message);
            log.info("push:{}",r);
            Object msgId = r.get("id");
            if(msgId!=null) {
                message.setMsgId(Integer.parseInt(msgId.toString()));
            }
            else
                message.setMsgId(0);
            message.setEffTime(DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"));

            WebSocketServer.sendInfo(JSON.toJSONString(JSON.toJSON(message)), toUserId,"","");
        } catch (Exception e) {
            //System.err.println(e.getMessage());
            log.error("push msg error:"+e.getMessage());
            return R.error(e.getMessage());
        }

        return R.ok();
    }

你可能感兴趣的:(springcloud,alibaba,websocket,spring,cloud,java)