Magician 是一个异步非阻塞的网络协议解析包,支持Http, WebSocket, UDP等协议
JDK11+
<dependency>
<groupId>com.github.yuyenews</groupId>
<artifactId>Magician</artifactId>
<version>最新版</version>
</dependency>
<!-- 这个是日志包,支持任意可以跟slf4j桥接的包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.12</version>
</dependency>
public class DemoHandler implements MagicianHandler<MagicianRequest> {
@Override
public void request(MagicianRequest magicianRequest) {
// 响应数据
magicianRequest.getResponse()
.sendJson(200, "{'status':'ok'}");
}
}
Magician.createTCPServer()
.handler("/", new DemoHandler())
.bind(8080);
EventGroup ioEventGroup = new EventGroup(1, Executors.newCachedThreadPool());
EventGroup workerEventGroup = new EventGroup(10, Executors.newCachedThreadPool());
// 当前EventRunner没任务的时候,允许从其他EventRunner窃取任务
workerEventGroup.setSteal(EventEnum.STEAL.YES);
Magician.createTCPServer(ioEventGroup, workerEventGroup)
.handler("/", new DemoHandler())
.bind(8080);
// 监听几个端口,ioEventGroup的第一个参数就写几
EventGroup ioEventGroup = new EventGroup(2, Executors.newCachedThreadPool());
EventGroup workerEventGroup = new EventGroup(10, Executors.newCachedThreadPool());
// 当前EventRunner没任务的时候,允许从其他EventRunner窃取任务
workerEventGroup.setSteal(EventEnum.STEAL.YES);
TCPServer tcpServer = Magician
.createTCPServer(ioEventGroup, workerEventGroup)
.handler("/", new DemoHandler())
tcpServer.bind(8080);
tcpServer.bind(8088);
只需要在创建http服务的时候加一个handler即可
Magician.createTCPServer()
.handler("/", new DemoHandler())
.webSocketHandler("/websocket", new DemoSocketHandler())
.bind(8080);
Magician.createUdpServer()
.handler(outputStream -> {
// outputStream 是ByteArrayOutputStream类型的
// 它是客户端发过来的数据,自行解析即可
}).bind(8088);
除了这种写法,也可以单独创建handler,在这里add进去