springboot简单集成t-io框架实现即时通讯


话不多说,直接上代码吧

先奉上官网地址文档:https://www.tiocloud.com/doc/tio/125?pageNumber=1
开源源码地址:https://gitee.com/tywo45/t-io

1、pom.xml添加相关依赖

<dependency>
    <groupId>org.t-io</groupId>
    <artifactId>tio-websocket-spring-boot-starter</artifactId>
    <version>3.6.0.v20200315-RELEASE</version>
</dependency>

版本我用的是3.6.0.v20200315-RELEASE这个,目前(2024年12月26日09:40:40)最高的版本(3.8.6.v20240801-RELEASE)好像需要jdk17以上了,不想升级jdk。

2、配置文件添加配置(application.yml)

tio:
  websocket:
    server:
      port: 9876
      heartbeat-timeout: 60000
      #是否支持集群,集群开启需要redis
    cluster:
      enabled: false
      redis:
        ip: 127.0.0.1
        port: 6379
        password: 123456
      # all: true
      # group: true
      # user: true
      # ip: true
      # channel: true

t-io是可以支持集群的,但是他很强大,一般中小型的项目单体就够了,喜欢集群就开启集群,配置redis,启动多个实例,做负载均衡就可以了。这里主要介绍单例模式。好了继续。。。

3、启动类添加注解

@EnableTioWebSocketServer

就是我们springboot的启动类,给你们看一个完整的吧

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.tio.websocket.starter.EnableTioWebSocketServer;

@SpringBootApplication
@EnableTioWebSocketServer
public class WebsocketApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(WebsocketApplication.class, args);
    }
}

到这里springboot简单集成t-io就已经完成了,启动项目就可以用了,简单吧。
但是怎么用呢?接下来就看我们的业务如何去使用

4、添加消息接收处理类,包括连接握手,消息发送都在这里面

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tio.common.starter.annotation.TioServerMsgHandler;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.common.WsSessionContext;
import org.tio.websocket.server.handler.IWsMsgHandler;

import java.util.Map;
import java.util.Objects;

/**
 * @author tanyaowu
 * 2017年6月28日 下午5:32:38
 */
@TioServerMsgHandler
@Component
public class ShowcaseWsMsgHandler implements IWsMsgHandler {
   
	private static Logger log = LoggerFactory.getLogger(ShowcaseWsMsgHandler.class);

	/**
	 * 握手时走这个方法,业务可以在这里获取cookie,request参数等
	 */
	@Override
	public HttpResponse handshake(HttpRequest request, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
   
		String clientip = request.getClientIp();
		String groupId 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值