springboot socketio
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion> <groupId>com.sys</groupId>
<artifactId>springboot-socketio</artifactId>
<version>0.0.-SNAPSHOT</version>
<packaging>jar</packaging> <name>springboot-socketio</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.corundumstudio.socketio/netty-socketio -->
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
2 启动加载 socket
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; @Component
@Order(value=)
public class MyCommandLineRunner implements CommandLineRunner {
private final SocketIOServer server; @Autowired
public MyCommandLineRunner(SocketIOServer server) {
this.server = server;
} @Override
public void run(String... args) throws Exception {
server.start();
System.out.println("socket.io启动成功!");
}
}
3 建立连接
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import java.util.ArrayList;
import java.util.Date;
import java.util.UUID; @Component
public class MessageEventHandler {
public static SocketIOServer socketIoServer;
public static ArrayList<UUID> listClient = new ArrayList<>();
//static final int limitSeconds = 60; @Autowired
public MessageEventHandler(SocketIOServer server) {
MessageEventHandler.socketIoServer = server;
} @OnConnect
public void onConnect(SocketIOClient client) {
listClient.add(client.getSessionId());
System.err.println(listClient.size());
System.out.println("客户端:" + client.getSessionId() + "已连接");
} @OnDisconnect
public void onDisconnect(SocketIOClient client) {
System.out.println("客户端:" + client.getSessionId() + "断开连接");
listClient.remove(client.getSessionId());
} @OnEvent(value = "messageevent") //value是监听事件的名称
public void onEvent(SocketIOClient client, AckRequest request, Object data) {
//System.out.println("发来消息:" + data.toString());
//socketIoServer.getClient(client.getSessionId()).sendEvent("messageevent", "back data"+new Date().getTime());
} public static void sendBuyLogEvent() { //这里就是向客户端推消息了
long dateTime = new Date().getTime(); for (UUID clientId : listClient) {
if (socketIoServer.getClient(clientId) == null) continue;
socketIoServer.getClient(clientId).sendEvent("messageevent", dateTime, );
}
} }
4 springboot 启动类SpringbootSocketioApplication 配置socket bean
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean; import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.sys.demo.kafka.KafkaSender; @SpringBootApplication
public class SpringbootSocketioApplication { public static void main(String[] args) {
ConfigurableApplicationContext context =SpringApplication.run(SpringbootSocketioApplication.class, args);
//SpringApplication.run(SpringBootKakfaApplication.class, args);
/*KafkaSender sender = context.getBean(KafkaSender.class); for (int i = 0; i < 3; i++) {
//调用消息发送类中的消息发送方法
sender.send(); try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} */ }
@Bean
public SocketIOServer socketIOServer() {
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration(); String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){ //在本地window环境测试时用localhost
System.out.println("this is windows");
config.setHostname("localhost");
} else {
config.setHostname("123.123.111.222"); //部署到你的远程服务器正式发布环境时用服务器公网ip
}
config.setPort(); /*config.setAuthorizationListener(new AuthorizationListener() {//类似过滤器
@Override
public boolean isAuthorized(HandshakeData data) {
//http://localhost:8081?username=test&password=test
//例如果使用上面的链接进行connect,可以使用如下代码获取用户密码信息,本文不做身份验证
// String username = data.getSingleUrlParam("username");
// String password = data.getSingleUrlParam("password");
return true;
}
});*/ final SocketIOServer server = new SocketIOServer(config);
return server;
} @Bean
public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
return new SpringAnnotationScanner(socketServer);
} }
5 监听kafka 发送消息给客户端
package com.sys.demo.kafka; import java.util.Optional;
import java.util.UUID; import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component; import com.sys.demo.MessageEventHandler; @Component
public class KafkaReceiver {
@Autowired
private MessageEventHandler messageEventHandler;
@KafkaListener(topics = {"mycall_out"})
public void listen(ConsumerRecord<?, ?> record) {
Optional<?> kafkaMessage = Optional.ofNullable(record.value());
if (kafkaMessage.isPresent()) {
Object message = kafkaMessage.get();
System.err.println("to client message:"+message);
for (UUID clientId : messageEventHandler.listClient) {
if (messageEventHandler.socketIoServer.getClient(clientId) == null)
continue;
//发送消息
messageEventHandler.socketIoServer.getClient(clientId).sendEvent("messageevent", message);
}
} }
}
springboot socketio的更多相关文章
- SpringBoot项目集成socketIo实现实时推送
netty-socketio maven依赖 <dependency> <groupId>com.corundumstudio.socketio</groupId> ...
- springBoot实现socketio
https://github.com/mrniko/netty-socketio-demo https://github.com/mrniko/netty-socketio
- netty-socketio(一)之helloworld,与springboot整合
netty-socketio是一个开源的Socket.io服务器端的一个java的实现, 它基于Netty框架. 1.参考资料 (1)netty-socketio项目github地址: https:/ ...
- netty-socketio整合springboot消息推送
netty-socketio整合springboot消息推送 1.netty-socketio消息推送 1)在项目中常常涉及到消息推送的情况,消息推送要求的实时性,使用传统的方式已经不能满足需求了: ...
- 解决 Springboot Unable to build Hibernate SessionFactory @Column命名不起作用
问题: Springboot启动报错: Caused by: org.springframework.beans.factory.BeanCreationException: Error creati ...
- 【微框架】Maven +SpringBoot 集成 阿里大鱼 短信接口详解与Demo
Maven+springboot+阿里大于短信验证服务 纠结点:Maven库没有sdk,需要解决 Maven打包找不到相关类,需要解决 ps:最近好久没有写点东西了,项目太紧,今天来一篇 一.本文简介 ...
- Springboot搭建web项目
最近因为项目需要接触了springboot,然后被其快速零配置的特点惊呆了.关于springboot相关的介绍我就不赘述了,大家自行百度google. 一.pom配置 首先,建立一个maven项目,修 ...
- Java——搭建自己的RESTful API服务器(SpringBoot、Groovy)
这又是一篇JavaWeb相关的博客,内容涉及: SpringBoot:微框架,提供快速构建服务的功能 SpringMVC:Struts的替代者 MyBatis:数据库操作库 Groovy:能与Java ...
- 解决 SpringBoot 没有主清单属性
问题:SpringBoot打包成jar后运行提示没有主清单属性 解决:补全maven中的bulid信息 <plugin> <groupId>org.springframewor ...
随机推荐
- Houdini Mac 添加external editor
我的尝试: 1. 找到houdini.env文件 2. 修改env文件,添加 EDITOR = ""/Applications/Sublime Text.app/Contents ...
- JAVA中生成指定位数随机数的方法总结
JAVA中生成指定位数随机数的方法很多,下面列举几种比较常用的方法. 方法一.通过Math类 public static String getRandom1(int len) { int rs = ( ...
- 小于K的两数之和
给你一个整数数组 A 和一个整数 K,请在该数组中找出两个元素,使它们的和小于 K但尽可能地接近 K,返回这两个元素的和. 如不存在这样的两个元素,请返回 -1. 示例1: 输入:A = [34,23 ...
- 记一次偶发的bug排查——redis-py-cluster库的bug
排查流水账: 通过平台监控,发现很多偶发的查看推荐列表的接口时延大于0.5s 写单元测试,不能重现.在测试环境不能重现.只有在正式环境可以偶发重现. 通过日志埋点,等待重现 不断地加日志埋点后发现耗 ...
- Java之布尔运算
对于布尔类型boolean,永远只有true和false两个值. 布尔运算是一种关系运算,包括以下几类 比较运算符:>,>=,<,<=,==,!= 与运算 && ...
- salt远程实现go编译重启
使用salt实现jenkins发版时,远程对go项目编译重启 1.go 版本1.12 使用go mod 2.设置go镜像 GOPROXY="https://goproxy.io" ...
- 一文看懂JS继承
继承是OOP中大家最喜欢谈论的内容之一,一般来说,继承都两种方式:接口继承和实现继承而JavaScript中没有接口继承需要的方法,因此只能依靠实现继承.在讲继承的实现之前,我们首先来回顾一下什么是继 ...
- Ribbon和Nignx的区别
Ribbon属于客户端负载均衡:在调用接口的时候,会通过服务别名到eureka上获取服务的信息列表,缓存到jvm本地,在本地采用RPC远程调用技术去调用接口,实现负载均衡.可以设置调用的规则是请求总数 ...
- Java开发笔记(一百五十一)Druid连接池的用法
C3P0连接池自诞生以来在Java Web领域反响甚好,业已成为hibenate框架推荐的连接池.谁知人红是非多,C3P0在大型应用场合中暴露了越来越多的局限性,包括但不限于下列几点:1.C3P0管理 ...
- k8s集群node节点一直NotReady, 且node节点(并非master)的kubelet报错:Unable to update cni config: No networks found in /etc/cni/net.d
若要转载本文,请务必声明出处:https://www.cnblogs.com/zhongyuanzhao000/p/11401031.html 问题: 集群搭建的过程中,master节点初始化成功,但 ...