springboot整合websocket实现页面在线客服聊天,并且解决无法注入实例的问题

本文采用现在流行的springboot框架整合websocket实现在线客服的聊天功能,代码实现如下:

pom.xml:




	4.0.0

	com.zqj
	webchat
	0.0.1-SNAPSHOT

	webchat
	
	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.2.RELEASE
	

	
		UTF-8
		1.8
		1.8
	

	
		
		
			org.springframework.boot
			spring-boot-starter-web
			
				
					org.springframework.boot
					spring-boot-starter-tomcat
					compile
				
			
		
		
			org.springframework.boot
			spring-boot-starter-tomcat
			provided
		
		
		
		
			org.springframework.boot
			spring-boot-starter-websocket
		
		
		
		
			org.projectlombok
			lombok
			1.18.0
		
	
	
	
		
			
				org.apache.maven.plugins
				maven-compiler-plugin
			
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

springboot入口类:

package com.zqj.chat;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@SpringBootApplication
public class WebChatApplication 
{
    public static void main( String[] args )
    {
        SpringApplication.run(WebChatApplication.class, args);
    }
    
    /**
     * 
    * @Title: serverEndpointExporter  
    * @Description: 检测服务类实现
    * @return ServerEndpointExporter 
    * @throws
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter (){
        return new ServerEndpointExporter();
    }
}

websocket服务实现WebSocketService

package com.zqj.chat.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketService {
	
	public static Map sessionMap = new ConcurrentHashMap();
	
	@OnOpen
	public void onOpen(@PathParam("userId") String userId,Session session) {
		log.info("WebSocketService onOpen: "+userId);
		if(sessionMap == null) {
			sessionMap = new ConcurrentHashMap();
		}
		sessionMap.put(userId, session);
	}
	
	@OnClose
	public void OnClose(@PathParam("userId") String userId) {
		log.info("WebSocketService OnClose: "+userId);
		sessionMap.remove(userId);
	}
	@OnMessage
	public void OnMessage(@PathParam("userId") String userId,Session session,String message) {
		log.info("WebSocketService OnMessage: "+message);
		for(Session session_ : sessionMap.values()) {
			session_.getAsyncRemote().sendText(message);
		}
	}
	
	@OnError
	public void error(Session session, Throwable t) {
		
		t.printStackTrace();
	}
}

测试页面:





    聊天室
    
		
		
		
		
		


     

帐号 昵称 开始聊天

打开浏览器访问:http://127.0.0.1:8080/webchat.html,界面如下:

springboot整合websocket实现页面在线客服聊天,并且解决无法注入实例的问题_第1张图片



在开发过程中遇到了使用注解@ServerEndpoint时,会发生无法自动注入其他实例的情况,解决方案如下:

先写一个config类:

package com.libang.manage.websocket;

import javax.websocket.server.ServerEndpointConfig.Configurator;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyEndpointConfigure extends Configurator implements
		ApplicationContextAware {

	private static volatile BeanFactory context;

	@Override
	public  T getEndpointInstance(Class 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;
	}

}

将WebsocketService类上的@ServerEndpoint(value="/websocket/{userId}")改成

@ServerEndpoint(value="/websocket/{userId}",configurator=MyEndpointConfigure.class) 

就可以完美的使用@Autowired注入实例。


你可能感兴趣的:(springboot整合websocket实现页面在线客服聊天,并且解决无法注入实例的问题)