Spring Boot + Java爬虫 + 部署到Linux(四、使用WebSocket实现消息推送,并解决websocket中的autowired问题)_gg_yangliyang的博客-程序员秘密

技术标签: 消息推送  爬虫  autowired  websocket  Spring Boot  Spring boot  

    在爬虫的过程中,我们有时需要实时的爬取的过程显示出来。如果采用正常的http协议,只有客户端发送请求,服务器才能做出响应,但是爬虫是在后端跑的,什么时候产生什么信息,没法直接发送给前端。可能我们会想到一个办法,就是后端维护一个缓存信息,然后前端定时的轮询这个信息,并取走显示出来。但是有了websocket,服务器就可以直接向客户端发送信息了。相比轮询有以下优点:

1. 节约带宽。 不停地轮询服务端数据这种方式,使用的是http协议,head信息很大,有效数据占比低, 而使用WebSocket方式,头信息很小,有效数据占比高。
2. 无浪费。 轮询方式有可能轮询10次,才碰到服务端数据更新,那么前9次都白轮询了,因为没有拿到变化的数据。 而WebSocket是由服务器主动回发,来的都是新数据。

3. 实时性,考虑到服务器压力,使用轮询方式不可能很短的时间间隔,否则服务器压力太多,所以轮询时间间隔都比较长,好几秒,设置十几秒。 而WebSocket是由服务器主动推送过来,实时性是最高的。

所以我们就想通过websocket来实现消息的推送功能。在实现的过程中遇到了一个很大的问题,那就是autowired在websocket中失效了。最后各种找,还是在csdn里找到了。

首先呢,要在项目里加上websocket的依赖,在pom.xml的dependencies里加上这个:

<dependency>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>

然后开始写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();//标准配置
    }
//如果不需要autowired,则下面这个函数就不需要了
    @Bean
    public MyEndpointConfigure newConfigure()
    {
        return new MyEndpointConfigure();
    }
}

如果需要在websocket里用到autowired,则还要实现下面这个类MyEndPointConfigure,也就是上面这段代码的第二个函数的返回类型。如果没用到,就别画蛇添足了。

import javax.websocket.server.ServerEndpointConfig;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 
 * 
 *这个类的核心就是getEndpointInstance(Class clazz)这个方法。 
   定义了获取类实例是通过ApplicationContext获取。
 *
 *
 */
public class MyEndpointConfigure extends ServerEndpointConfig.Configurator implements ApplicationContextAware
{
    private static volatile BeanFactory context;

    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException
    {
         return context.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        System.out.println("auto load"+this.hashCode());
        MyEndpointConfigure.context = applicationContext;
    }
}

最后呢,实现webscoket的主类:



import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
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.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



/**
 * 默认的实现,AutoWired注入失败,猜测是因为@ServerEndpoint管理了,不归spring了
 * 解决方法1:定义一个Config,将其给spring管理
 * 缺点:不是正常的管理。。。
 * 
 *
 */
@Component
@ServerEndpoint(value = "/websocket",configurator=MyEndpointConfigure.class)//如果不需要autowired,则configuator不需要了
//上面的这个value,就相当于我们的websocket服务器地址,客户端通过ws://ip:port/value,就能和服务器建立连接了。
public class MyWebSocket {
	//@Autowired 
	//private  GalleryDAO galleryDAO;
	//@Autowired 
	//private  ImageDAO imageDAO;
	
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

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

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

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

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @throws IOException */
    @OnMessage
    public void onMessage(String message, Session session)  {
    	//可以在这根据客户端的消息,做一些操作
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message)  {
        try {
			this.session.getBasicRemote().sendText(message);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //this.session.getAsyncRemote().sendText(message);
    }
    public void sendMessage(String message,Session session)  {
        try {
			session.getBasicRemote().sendText(message+"\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //this.session.getAsyncRemote().sendText(message);
    }


//    /**
//     * 群发自定义消息
//     * */
//    public static void sendInfo(String message) throws IOException {
//        for (MyWebSocket item : webSocketSet) {
//            try {
//                item.sendMessage(message);
//            } catch (IOException e) {
//                continue;
//            }
//        }
//    }

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

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

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

关于这个autowired的问题,这是其中一个简单的解决方法,但据说不太好。更深入的了解,在springboot中的websocket无法自动注入的,可以参考这篇文章解决springboot websocket无法注入其他类。这篇文章最下面也贴了stackoverflow的相关地址,英语好的可以看看。

websocket在前端要怎么配置呢?下面是javascript的实现代码:需要注意的是这样写一点开网页就会自动建立连接和初始化。也可以写在函数里,来实现点击某个按钮再建立连接。

            var websocket = null;

	    //判断当前浏览器是否支持WebSocket
	    if('WebSocket' in window){
	        
	        init_websocket(websocket);
	    }
	    else{
	        alert('Not support websocket')
	    }
		function init_websocket(websocket){
			websocket = new WebSocket("ws://localhost:8080/websocket");//这个websocket就对应上面的ServerEndPoint的value
                                                  //,host和port则是服务器的host和port,new这个对象,就会建立连接。
			//连接发生错误的回调方法
		    websocket.onerror = function(){
		        //错误处理
		    };

		    //连接成功建立的回调方法
		    websocket.onopen = function(event){
		    	//成功处理
		    }

		    //接收到消息的回调方法
		    websocket.onmessage = function(event){
		        //event.data里面包含了接收到的消息,可以通过js将消息处理、显示出来
		    }

		    //连接关闭的回调方法
		    websocket.onclose = function(){
		        //关闭处理
		    }

		    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
		    window.onbeforeunload = function(){
		        websocket.close();
		    }
		}
                function sendmessgae(msg){
                        websocket.send(msg);
                }
服务器的websocket和客户端的websocket是怎么对应的呢?可以看到一些函数(注解)都差不多。其中服务器和客户端的onopen、onclose、onerror都是一一对应的。但是onmessage和 sendmessage,这两个方法是相互对应的,即客户端的sendmessgae,会触发服务器端的onmessage。同理,服务器端的sendMessage也会触发客户端的onMessage。
    通过这两个方法,我们就能相互的传递信息了。通过服务器对客户端实时的发送信息,用户就能实时的看到爬虫的进度了。
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/gg_yangliyang/article/details/80867102

智能推荐

推荐几款Web性能测试工具_是用于测试 web 应用性能和功能的工具有哪些_佞臣888的博客-程序员秘密

专业的软件测试工程师至少要掌握一到两种测试工具,而作为普通软件开发者,或多或少掌握一些测试方法和技巧。随着用户对科技产品用户体验度的上升,产品发布前的测试工作变得尤为重要。工欲善其事必先利其器,下面本文就推荐五款非常流行的Web性能测试工具。1.HP LoadrunnerLoadrunner——相信不少开发者都知道这款工具,是目前最受欢迎的一款性能测试工具。它是一种预测系统行为和性能的负载测...

Server 2019 WSUS安装详细步骤图解教程_奋斗的小青年I的博客-程序员秘密

什么是WSUS?WSUS是Windows Server Update Services的简称,WSUS支持微软公司全部产品的更新,包括Windwos、Office、SQL Server、MSDE和Exchange Server等内容。

阿里首席架构师分享的Java工程师职业规划_互联网架构的博客-程序员秘密

相关阅读:如何在 3 年内摆脱“普通程序员”标签京东应用架构设计与治理互联网技术(java框架、分布式、集群)干货视频大全,不看后悔!(免费下载)一初级程序员:做一些静态...

linux非root 配置java环境变量_sleeper01的博客-程序员秘密

编辑配置文件vi ~/.bashrc设置环境变量JAVA_HOME=/data/app/tools/jdk1.8.0_201CLASSPATH=$JAVA_HOME/lib:$JAVA_HOME/jre/libPATH=$PATH:$JAVA_HOME/bin:$JAVA_HOME/jre/binexport PATH CLASSPATH JAVA_HOME使变量生效source...

Ceph存储的三种模式 部署MDS文件存储 RBD块存储 RGW对象存储_ceph rbd rgw_我的紫霞辣辣的博客-程序员秘密

Mds文件存储1. 将监控节点制作成文件系统我们这里是考虑到虚拟机环境,所以将监控节点制作成文件系统,生产环境中尽量不要这么做。- 在管理端admin节点操作cd /etc/ceph # 必须切换到工作目录下,因为ceph认证的机制是检索当前目录下的密钥环文件ceph.bootstrap-rgw.keyringceph-deploy mds create mon01 mon02 mon03 # 将mon01 mon02 mon03制作成文件系统格式- 在管理节点查看各个节点的mds

随便推点

C语言学习笔记---memcpy函数的用法_ZZ·P的博客-程序员秘密

由src指向地址为起始地址的连续n个字节的数据复制到以destin指向地址为起始地址的空间内

双非科班出身,如何逆袭拿到大厂 Offer?| 程序员有话说_CSDN 程序人生的博客-程序员秘密

作者 |进击的鹅厂小白责编 | 伍杏玲出品 | 程序人生(ID:coder_life)在互联网行业,入行的第一份工作很大程度上决定了以后职业发展的高度。有些双非的同学认为自己校招进不了...

docker 构建私有仓库遇到的常见问题_为什么创建docker私有仓库重启不了_Waldenz的博客-程序员秘密

构建私有仓库拉取registry镜像,构建私有的镜像注册服务器docker pull registry运行容器docker run --restart=always -d -p 5000:5000 -v /myregistry:/var/lib/registry registry-d后台运行,不会有交互终端-it运行就会有一个终端,退出容器后,容器也停止并退出了(...

UVIEW----可滑动的弹窗选择搜索框_uview 搜索框_weixin_44126737的博客-程序员秘密

上面文本部分,如果超出了,可以上下滑动,而搜索框不动。&lt;template&gt; &lt;view&gt; &lt;button type="default" @click="open"&gt;打开&lt;/button&gt; &lt;u-popup v-model="popup" mode="center" border-radius="15" width="70%" height="400px"&gt; &lt;view class="wllw-wi...

SpringBoot基础——SpringBoot配置_XHHP的博客-程序员秘密

1、配置文件两种配置文件SpringBoot使用一个全局的配置文件,配置文件名是固定的;application.propertiesapplication.yml配置文件的作用:修改SpringBoot自动配置的默认值;SpringBoot在底层都给我们自动配置好application.properties配置示例:server.port=8080application...

推荐文章

热门文章

相关标签