<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
在启动类上添加一个bean
@SpringBootApplication
public class CommonCodeApplication {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
public static void main(String[] args) {
SpringApplication.run(CommonCodeApplication.class, args);
}
}
核心代码
@Component
@ServerEndpoint("/websocket2/{username}")
@Slf4j
public class WebSocketDemo2 {
private static Map<String, WebSocketDemo2> webSocketMap = new HashMap<>();
private static Integer onlineUserCount = 0;
private Session session;
private String username;
/**
* 建立连接
* @param username
* @param session
*/
@OnOpen
public void onOpen(@PathParam("username") String username, Session session){
this.username = username;
this.session = session;
webSocketMap.put(username, this);
int count = addOnlineUser();
log.info("当前在线用户:{}", count);
}
/**
* 关闭连接
* @param username
*/
@OnClose
public void onClose(@PathParam("username") String username){
webSocketMap.remove(username);
int count = reduceOnlineUser();
log.info("当前在线用户:{}", count);
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonObject = JSONUtil.parseObj(message);
String target = jsonObject.getStr("target");
String msg = jsonObject.getStr("msg");
if (target.equals("all")){
sendMessageAll(msg);
}
}
/**
* 给特定的人发消息,用于业务中调用
* @param usernames
* @param message
* @throws IOException
*/
public void sendMessageSpecial(List<String> usernames, String message) throws IOException {
for (String username : webSocketMap.keySet()) {
for (String target : usernames) {
if (username.equals(target)){
webSocketMap.get(username).session.getBasicRemote().sendText(message);
}
}
}
}
/**
* 给所有人发消息
* @param message
* @throws IOException
*/
public void sendMessageAll(String message) throws IOException {
for (WebSocketDemo2 item : webSocketMap.values()) {
System.out.println("消息发送");
item.session.getBasicRemote().sendText(message);
}
}
public void sendMessage(String message) throws IOException {
session.getBasicRemote().sendText(message);
}
/**
* 用户离线
* @return
*/
public int reduceOnlineUser(){
return -- onlineUserCount;
}
/**
* 累加在线用户
* @return
*/
public int addOnlineUser(){
return ++ onlineUserCount;
}
}
实现消息推送只要在业务代码中调用sendMessageSpecial()方法即可。
@RestController
@RequestMapping("/websocket")
public class WebSocketController {
@Autowired
private WebSocketDemo2 webSocketDemo2;
@GetMapping("/t1")
public String test1() throws IOException {
System.out.println("这是业务代码...");
String message = "消息被督办了!";
List<String> usernames = new ArrayList<>();
usernames.add("张三");
usernames.add("李四");
usernames.add("王五");
webSocketDemo2.sendMessageSpecial(usernames, message);
return "ok";
}
}
然后调用刚才的业务接口测试:http://localhost:8080/websocket/t1
调用成功后可以看到三个窗口中都收到了消息