关于java:Solon-也是-SSE-开发的后端优选最近因-chatGPT-火了-SSE

1次阅读

共计 1714 个字符,预计需要花费 5 分钟才能阅读完成。

Solon 2.3.6 在开发异步接口时,顺带也为 Solon Web 提供了 SSE (Server-Sent Events) 协定的反对插件:

<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon.web.sse</artifactId>
</dependency>

如果不熟 SSE 的,能够通过搜索引擎查问理解下。// 集体还是感觉 ws 更不便用:)

应用示例

按群里用户的要求,体验形式尽量采纳大家相熟的命名与格调。

@Controller
public class SseDemoController {static Map<String, SseEmitter> emitterMap = new HashMap<>();

    @Mapping("/sse/{id}")
    public SseEmitter sse(String id) {
         //3000L 是后端异步超时
         return new SseEmitter(3000L)
                .onCompletion(() -> emitterMap.remove(id))
                .onError(e -> e.printStackTrace())
                .onInited(s -> emitterMap.put(id, s)); // 在 onInited 里,能够发消息(初始化实现之前,是不能发消息的)}

    @Mapping("/sse/put/{id}")
    public String ssePut(String id) {SseEmitter emitter = emitterMap.get(id);
        if (emitter == null) {return "No user:" + id;}

        String msg = "test msg ->" + System.currentTimeMillis();
        emitter.send(new SseEvent().id(Utils.guid()).data(msg).reconnectTime(1000L));

        return "Ok";
    }

    @Mapping("/sse/del/{id}")
    public String sseDel(String id) {SseEmitter emitter = emitterMap.get(id);
        if (emitter != null) {emitter.complete();
        }

        return "Ok";
    }
}

注意事项

  • 这个插件可能须要把线程数调大些
# 服务 http 最小线程数(默认:0 示意主动,反对固定值 2 或 内核倍数 x2)server.http.coreThreads: 0 
#服务 http 最大线程数(默认:0 示意主动,反对固定值 32 或 内核倍数 x32)server.http.maxThreads: 0

更多配置可参考:《利用罕用配置阐明》

  • 对于超时的阐明

超时是指服务端的异步超时,默认为 30000L(即 30 秒)。其中,0L 代表默认,-1L 代表不超时。

  • 进步连接数

要用好,后端超时、前端重连工夫以及线程数配置。

Solon 是什么开源我的项目?

一个,Java 新的生态型利用开发框架 。它从零开始构建,有本人的标准规范与凋谢生态(历时五年,已有寰球第二级别的生态)。与其余框架相比, 它解决了两个重要的痛点:启动慢,费内存

解决痛点?

因为 Solon Bean 容器的独特设计,不会因为扩大依赖变多而启动很慢(开发调试时,省时、痛快)!以出名开源我的项目“小诺”为例:

  • “snowy-spring 版”启动 30-50 秒
  • “snowy-solon 版”启动 3 - 5 秒,内存省了 1 /3(有趣味的,欢送拉取代码体验)

所谓:“工夫就是生命,效率就是金钱”,“天下文治,唯快不破”。

绝对于 Spring Boot 和 Spring Cloud 的我的项目,有什么特点?

  • 启动快 5 ~ 10 倍。(更快)
  • qps 高 2~ 3 倍。(更高)
  • 运行时内存节俭 1/3 ~ 1/2。(更少)
  • 打包能够放大到 1/2 ~ 1/10;比方,300Mb 的变成了 23Mb。(更小)
  • 同时反对 jdk8, jdk11, jdk17, jdk20, graalvm native

我的项目仓库地址?

  • gitee:https://gitee.com/noear/solon
  • github:https://github.com/noear/solon
正文完
 0