spring|spring boot项目启动websocket
1. pom.xml引入:
org.springframework.boot
spring-boot-starter-websocket
2. 创建配置类:WebSocketConfig
@Configuration
@EnableCaching
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3. 自定义配置类(为了保证websocket能够像controller一样使用):SpringContextHelper
// 自定义配置类
@Component
public class SpringContextHelper extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
//通过手动注入applicationContext上下文获取Bean
private static volatile BeanFactory context;
@Override
public TgetEndpointInstance(Class clazz) throws InstantiationException {
return context.getBean(clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
SpringContextHelper.context = applicationContext;
}
}
4、创建websocket监听类:Web1
import com.alibaba.fastjson.JSON;
import com.epf.app.redis.SmsRedisService;
import com.epf.csce.config.SpringContextHelper;
import com.epf.csce.dao.BjMyCollectDao;
import com.epf.csce.dao.BjNewsTrendsDao;
import com.epf.csce.entity.BjMyCollectEntity;
import com.epf.csce.entity.BjNewsTrendsEntity;
import com.epf.csce.entity.WxSocketEntity;
import com.epf.csce.service.BjPopularRecommendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint(value= "https://www.it610.com/wxsmall/web1", configurator= SpringContextHelper.class)
@Component
public class Web1 {private static Logger log = LoggerFactory.getLogger(Web1.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
@Autowired
private SmsRedisService redisService;
@Autowired
private BjPopularRecommendService bjPopularRecommendService;
@Resource
private BjMyCollectDao bjMyCollectDao;
@Resource
private BjNewsTrendsDao bjNewsTrendsDao;
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
//加入set中
addOnlineCount();
//在线数加1
log.info("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
//从set中删除
subOnlineCount();
//在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
* @parammessage 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:" + message);
//群发消息
for (Web1 item: webSocketSet) {
String result= "";
try {
item.sendMessage(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @paramsession
* @paramerror
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 服务器主动推送
* @parammessage
* @throwsIOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
*/
public static void sendInfo(String message) throws IOException {
log.info(message);
for (Web1 item: webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
Web1.onlineCount++;
}
public static synchronized void subOnlineCount() {
Web1.onlineCount--;
}
}
推荐阅读
- Activiti(一)SpringBoot2集成Activiti6
- SpringBoot调用公共模块的自定义注解失效的解决
- 解决SpringBoot引用别的模块无法注入的问题
- 2018-07-09|2018-07-09 Spring 的DBCP,c3p0
- 17|17 关山松 第二课作业#公众号项目# D20
- RxJava|RxJava 在Android项目中的使用(一)
- Hacking|Hacking with iOS: SwiftUI Edition - SnowSeeker 项目(一)
- 靠QQ月入上万灰色暴利偏门的项目
- Spring|Spring Boot 整合 Activiti6.0.0
- Spring集成|Spring集成 Mina