Spring Boot + Java爬虫 + 部署到Linux(四、使用WebSocket实现消息推送,并解决websocket中的autowired问题)
2018-06-30 17:03
1186 查看
在爬虫的过程中,我们有时需要实时的爬取的过程显示出来。如果采用正常的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。
通过这两个方法,我们就能相互的传递信息了。通过服务器对客户端实时的发送信息,用户就能实时的看到爬虫的进度了。
阅读更多
相关文章推荐
- Spring Boot + Java爬虫 + 部署到Linux(八、Nginx实现反向代理、动静分离和websocket处理)
- Spring Boot + Java爬虫 + 部署到Linux(五、使用spring data JPA 实现数据访问层)
- IntelliJ IDEA中Spring Boot项目使用spring-boot-devtools无法实现热部署/热更新的问题解决
- 在Spring Boot框架下使用WebSocket实现消息推送
- 在Spring Boot框架下使用WebSocket实现消息推送
- 在Spring Boot框架下使用WebSocket实现消息推送
- 在Spring Boot框架下使用WebSocket实现消息推送
- 在Spring Boot框架下使用WebSocket实现消息推送
- 使用SpringBoot快速搭建WebSocket实现消息推送
- 在Spring Boot框架下使用WebSocket实现消息推送
- 在Spring Boot框架下使用WebSocket实现消息推送
- 在Spring Boot框架下使用WebSocket实现消息推送
- 在Spring Boot框架下使用WebSocket实现消息推送
- 在Spring Boot框架下使用WebSocket实现消息推送
- 详解在Spring Boot框架下使用WebSocket实现消息推送
- Spring Boot + Java爬虫 + 部署到Linux(六、后端Controller实现、下载文件以及登录验证拦截器)
- 在Spring Boot框架下使用WebSocket实现消息推送
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- spring boot 读取配置文件问题,不能使用@Autowired