SpringBoot集成WebSocket实现多个服务通信

spring boot + webSocket实现多个项目之间进行通信操作

作为spring cloud微服务多个服务之间进行通信

首先至少得有一个websocket服务端  与一个或多个 websocket客户端

已提供源码免费下载,Spring Cloud alibaba nacos注册中心+【websocket服务端和websocket客户端】两个服务

https://download.csdn.net/download/m0_37845840/14038629

一、首先无论是服务端还是客户端都需要添加的maven依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

二、Application启动类

由于WebSocketServer服务端类使用的是@Component注解
所以启动类需要用@ComponentScan对该类进行扫描

import com.test.www.socket.WebSocketServer;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
@EnableScheduling
@ComponentScan("com.test.www")
@MapperScan(value = {"com.test.www.mapper"})
public class Application {
    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(Application.class);
        ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
        WebSocketServer.setApplicationContext(configurableApplicationContext);
    }
}

三、WebSocketServer服务端的WebSocketConfig配置类

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();
    }
}

四、WebSocketServer服务端接受客户端请求连接的类

package com.example.socketserver.websocket;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Administrator
 * @description
 * @date 2021-01-07 10:09
 */
@Component
@ServerEndpoint(value = "/{ip}")
public class WebSocketServer {

    // 在多线程访问的时候,使用线程安全的ConCurrentHashMap对象
    private static ConcurrentHashMap<String, Session> connections = new ConcurrentHashMap<>();

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.applicationContext = applicationContext;
    }

    /**
     * 打开连接
     * @param session
     * @param ip
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("ip") String ip) {
        System.out.println("=====接受到的地址=====" + ip);
        // 接收到客户端的请求,可以做一些其他业务逻辑处理,比如可以把该IP存储到数据库
        // 避免当前服务断开后,与客户端服务失去连接
        // 这时就可以使用到预加载处理,项目当中自定义的MyApplicationRunner类
        connections.put(ip, session);
    }

    /**
     * 接收消息
     * @param text
     */
    @OnMessage
    public void onMessage(String text) {

    }

    /**
     * 异常处理
     * @param throwable
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 关闭连接
     * @param ip
     */
    @OnClose
    public void onClosing(@PathParam("ip") String ip) throws IOException {
        connections.remove(ip);
    }

    /**
     * 根据IP发送消息
     * @param ip
     * @param text
     */
    public void send(String ip, String text) {
        try {
            Session session = connections.get(ip);
            if (session != null && session.isOpen()) {
                session.getAsyncRemote().sendText(text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 遍历群发消息
     * @param text
     */
    public void send(String text) {
        for (ConcurrentHashMap.Entry<String, Session> entry : connections.entrySet()) {
            send(entry.getKey(), text);
        }
    }

}

五、SocketClient客户端服务发起连接的类

session.getBasicRemote().sendText()为同步发送
session.getAsyncRemote().sendText()为异步发送
当并发发送数据的时候避免阻塞,一般都使用异步

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;

@Component
@ClientEndpoint
public class SocketClient {

    // 服务端的IP和端口号
    private static final String URL = "192.168.1.1:8080";

    private Session session;

    @PostConstruct
    void init() {
        try {
            // 本机地址
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            String wsUrl = "ws://" + URL + "/" + hostAddress;
            URI uri = URI.create(wsUrl);
            session = container.connectToServer(SocketClient.class, uri);
        } catch (DeploymentException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开连接
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
    }

    /**
     * 接收消息
     * @param text
     */
    @OnMessage
    public void onMessage(String text) {

    }

    /**
     * 异常处理
     * @param throwable
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClosing() throws IOException {
        session.close();
    }

    /**
     * 主动发送消息
     */
    public void send(JSONObject json) {
        try {
            session.getAsyncRemote().sendText(json.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

 

 

 

  • 4
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
Spring Boot是一个用于构建独立的、生产级的Spring应用程序的框架。Netty是一个高性能的网络通信库,可以用于构建各种类型的网络应用。WebSocket是一种基于HTTP协议的双向通信协议,可以实现实时的双向通信。MyBatis Plus是一个基于MyBatis的增强工具,提供了更简单、更便捷的方式来操作数据库。 在Spring Boot中使用Netty和WebSocket可以实现实时的双向通信功能。可以通过使用Netty提供的WebSocket支持来处理WebSocket连接,然后使用Spring Boot中的其他组件来处理业务逻辑。可以使用MyBatis Plus来简化数据库操作,提供了一些常用的功能,如分页查询、条件查询等。 如果你想使用Spring Boot、Netty、WebSocket和MyBatis Plus来构建一个应用程序,你可以按照以下步骤进行操作: 1. 创建一个Spring Boot项目,并引入Netty、WebSocket和MyBatis Plus的相关依赖。 2. 配置Netty和WebSocket的相关参数,如端口号、路径等。 3. 创建WebSocket处理器,用于处理WebSocket连接和消息的收发。 4. 在WebSocket处理器中集成MyBatis Plus,可以通过注入Mapper来实现数据库操作。 5. 在Spring Boot的配置文件中配置数据库连接信息。 6. 创建业务逻辑类,处理具体的业务逻辑。 7. 在Spring Boot的启动类中配置Netty和WebSocket的相关配置,并启动应用程序。 通过以上步骤,你可以使用Spring Boot、Netty、WebSocket和MyBatis Plus来构建一个具有实时双向通信功能的应用程序。希望对你有帮助!如果你有更多的问题,可以继续问我。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值