WebSocket获取service层对象,操作数据库

来源:互联网 发布:nginx 域名无法访问 编辑:程序博客网 时间:2024/06/06 08:50

在websocket中操作数据库,需要加载已经配置好的spring中的配置文件,获取service层对象。在搭建好websocket条件下以下几种方法可实现
第一种,通过ContextLoader获取

SharedFarmUsersManager sharedFarmUsersManager = (SharedFarmUsersManager) ContextLoader.getCurrentWebApplicationContext().getBean("sfum");

第二种,通过加载整个配置文件,加载完之后再获取been,这种性能较差,不建议使用

ClassPathXmlApplicationContext cc = new ClassPathXmlApplicationContext(new String[] {"applicationContext-common.xml"});SharedFarmUsersManagerImpl bean1 = (SharedFarmUsersManagerImpl) cc.getBean("sharedFarmUsersManagerImpl");

第三种,通过Configurator获取httpsession,通过httpsession可获取service
第一步编写一个继承Configurator的类

import javax.servlet.http.HttpSession;import javax.websocket.HandshakeResponse;import javax.websocket.server.HandshakeRequest;import javax.websocket.server.ServerEndpointConfig;import javax.websocket.server.ServerEndpointConfig.Configurator;public class GetHttpSessionConfigurator extends Configurator{    @Override      public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {          HttpSession httpSession = (HttpSession) request.getHttpSession();          if(httpSession != null){              config.getUserProperties().put(HttpSession.class.getName(), httpSession);          }      }  }

第二步编写@ServerEndpoint,并在onOpen 方法中获取service

import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.atomic.AtomicInteger;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import javax.websocket.EndpointConfig;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.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.struts2.ServletActionContext;import org.directwebremoting.json.JsonUtil;import org.directwebremoting.json.parse.JsonParseException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import org.springframework.web.context.ContextLoader;import org.springframework.web.context.support.WebApplicationContextUtils;import com.alibaba.fastjson.JSON;import com.nmfz.app.action.SharedFarmUsers;import com.nmfz.app.manager.SharedFarmUsersManager;import com.nmfz.app.manager.impl.SharedFarmUsersManagerImpl;import net.sf.json.JSONObject;/** * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端。注解的值将被用于监听用户连接的终端访问URL地址。 *  configurator:通过GetHttpSessionConfigurator可以在onOpen方法中取得HttpSession,然后通过HttpSession的ServletContext容器可以取得spring的service,实现在websocket中变相注入spring bean。 * @author zho */@ServerEndpoint(value = "/websocket/chat",configurator=GetHttpSessionConfigurator.class)public class MyWebSocket{ //  private static final Log log = LogFactory.getLog(ChatAnnotation.class);  //  private WebSocketService webSocketService;    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。      private final static AtomicInteger onlineCount = new AtomicInteger(0);      //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识  //  private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();     private static List<MyWebSocket> clients = new ArrayList<>();    //与某个客户端的连接会话,需要通过它来给客户端发送数据    private Session session;      private HttpSession httpSession;//  ngs static int userid ;     @OnOpen      public void onOpen(Session session, EndpointConfig config) throws IOException, InterruptedException  {          System.out.println("Open!");        this.session = session;          this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());          if(httpSession != null){              ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(httpSession.getServletContext());              SharedFarmUsersManager sharedFarmUsersManager = (SharedFarmUsersManager) ctx.getBean("sfum");             List<?> list = sharedFarmUsersManager.selectListBySql("select name from f_yh where id=1", null);            System.out.println(list);        }          clients.add(this);  //当前客户端加入集合//      addOnlineCount();   //在线数加1,对应的创建一个上锁的方法        MyWebSocket.onlineCount.incrementAndGet();//在线数加1//      String message = "登录成功";//      broadcast(message);         sendLatestNews();//向此用户发送一条最新的偷菜记录    }  

第三步,由于HTTP协议与websocket协议的不同,导致没法直接从websocket中获取协议,放出去执行,会报空指针值异常,因为这个HttpSession并没有设置进去。而设置HttpSession。需要写一个继承ServletRequestListener的监听器。

import javax.servlet.ServletRequestEvent;import javax.servlet.ServletRequestListener;import javax.servlet.annotation.WebListener;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Component;/** * 作用:将所有request请求都携带上httpSession * @author zho * */@WebListener//配置Listener@Componentpublic class RequestListener implements ServletRequestListener {    public void requestInitialized(ServletRequestEvent sre)  {        //将所有request请求都携带上httpSession        ((HttpServletRequest) sre.getServletRequest()).getSession();    }    public RequestListener() {    }    public void requestDestroyed(ServletRequestEvent arg0)  {    }}
原创粉丝点击