【BDS-IHG&FB项目学习-01】--nginx webSocket反向代理配置

解决3个问题

  • 1. nginx单纯做域名的代理时配置的解决办法
  • 2. websocket中java类无法依赖注入的解决办法
  • 3. nginx 域名映射对websocket中url的配置影响问题的解决办法
    • nginx配置
    • js代码
    • java代码

1. nginx单纯做域名的代理时配置的解决办法

2. websocket中java类无法依赖注入的解决办法

3. nginx 域名映射对websocket中url的配置影响问题的解决办法

nginx配置

http{
	include       mime.types;
    default_type  application/octet-stream;
	//配置websocket时配置以下
	//-------websocket开始----------
	map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }
    //-------websocket结束-------
	upstream web_pools {
	      server 127.0.0.1:8888;//这里填写端口
	    }
		
	
    server {
        listen       80;
        server_name  ihg-tools.bds-analytics.com;//这里填写二级域名

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {   
				proxy_redirect off;
				proxy_set_header Host $host;
				proxy_set_header X-Real-IP $remote_addr;
				proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
				proxy_pass http://192.168.3.52:8888;//这里填写服务器ip,如果填写localhost将导致cookie丢失
        }
        //配置websocket时添加以下
        //-------websocket开始----------
        location /websocket {
		
			proxy_pass http://192.168.3.52:8888;
			proxy_redirect    off;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header Host $host;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

			proxy_http_version 1.1;
			proxy_set_header Upgrade $http_upgrade;
			proxy_set_header Connection $connection_upgrade;
			proxy_set_header Origin "";
		}
		//-------websocket结束----------
	}
}

js代码

 var socket;
        $(function () {
            if(typeof(WebSocket) == "undefined") {
                layerMsg("错误","您的浏览器不支持WebSocket");
            }else{
                // layerMsg("正确","您的浏览器支持WebSocket");
                // http://211.152.47.79:8888/websocket
                //路径与以上对应,部署服务器可以测试使用http://www.websocket-test.com/
                socket = new WebSocket("ws://ihg-tools.bds-analytics.com/websocket");
                //打开事件
                socket.onopen = function() {
                    send2service();//打开先看提醒
                    window.setInterval("send2service()",1000*120);//120秒发送一次消息
                };
                //获得消息事件
                socket.onmessage = function(msg) {
                    layerMsg("警告",msg.data)
                    //发现消息进入    开始处理前端触发逻辑
                };
                //关闭事件
                socket.onclose = function() {
                    console.log("Socket已关闭");
                };
                //发生了错误事件
                socket.onerror = function() {
                    layerMsg("错误","Socket发生了错误,此时可以尝试刷新页面");
                    //此时可以尝试刷新页面
                }

            }

        });
       function send2service() {
           socket.send("hi,i am jack!");
       }

java代码

package com.bds.ihgfb.util;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.bds.ihgfb.model.StatusBean;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.impl.SimpleDataSource;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * className:WebSocketServer
 * discription:
 * author:luRuiHua
 * createTime:2019-07-08 17:06
 */
@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {

    static Log log= LogFactory.get(WebSocketServer.class);


//解决websocket依赖注入失败问题---开始-------------------------
    //  这里使用静态,让 service 属于类
    private static NutDao dao;
    // 注入的时候,给类的 service 注入
    @Autowired
    @Qualifier("xiaohongshu")
    public void setDao(NutDao dao){
        WebSocketServer.dao = dao;
    }
//解决websocket依赖注入失败问题---结束-------------------------

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;


    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口的信息:"+session+"-----"+message);
        String s = checkXhsFail();
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                if ("fail".equals(s)){
                    sendMessage("请打开手机,检查是否存在滑块");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }




    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public String checkXhsFail(){
        System.out.println("*********************定时任务开始执行*******************");
//        Dao dao = getDao();
        //创建sql语句
        Sql sql = Sqls.create("select count(0) as count,status from t_note_simple_task group by status");
        //设置返回结果
        sql.setCallback(Sqls.callback.entities());
        Entity<StatusBean> entity = dao.getEntity(StatusBean.class);
        sql.setEntity(entity);
        //执行sql语句
        dao.execute(sql);
        //获取返回结果
        List<StatusBean> list = sql.getList(StatusBean.class);
        int count = 0;

        for (int i =0;i<list.size();i++){
            StatusBean statusBean = list.get(i);
            int status = statusBean.getStatus();
            if (status==4){
                count = statusBean.getCount();
            }
        }
        if (count>=1){
            System.out.println("》》推送《《");
            return "fail";//如果存在4,推送消息
        }else {
            return "suc";
        }
    }

   

}

你可能感兴趣的:(java)