Solon v2.7.5

分享:Solon + Vert.x 开发响应式服务

</> markdown

此分享,由社区成员(阿南同学)提供或协助。在容器应用上,提供发散参考

Vert.x 是有名的响应式开发框架,但是缺容器支持;Solon 的容器“微小”。两相聚合特点,甚好。(提示:Solon 自己也是有响应式开发接口:solon.web.flux

1、主类

启动 Solon 容器:demo/App.class

@SolonMain
public class App {
    public static void main(String[] args) {
        Solon.start(App.class, args);
    }
}

2、添加 Vert.x 配置类

构建 vertx 实例并关联 solon 的生命周期。demo/VertxConfig.class

@Configuration
public class VertxConfig implements LifecycleBean {
    @Inject
    Vertx vertx;

    @Bean
    public Vertx vertx(){
        return Vertx.vertx(); //主要是给别的地方注入用
    }

    @Override
    public void start() throws Throwable {
        for(Verticle verticle : Solon.context().getBeansOfType(Verticle.class)){
            vertx.deployVerticle(verticle);
        }
    }

    @Override
    public void stop() throws Throwable {
        vertx.close();
    }
}

3、启动 http-server

定义 Http Verticle:demo/VertxHttpVerticle.class

@Component
public class VertxHttpVerticle extends AbstractVerticle {
    HttpServer server;

    @Inject
    HelloService helloService;

    @Override
    public void start() {
        server = vertx.createHttpServer();

        server.requestHandler(req ->{
            HttpServerResponse resp = req.response();
            resp.putHeader("content-type", "text/plain");
            resp.end(helloService.hello());
        }).listen(8181);
    }

    @Override
    public void stop() throws Exception {
        if (server != null) {
            server.close();
            server = null;
        }
    }
}

@Component
public class HelloService{
    public String hello(){
        return "Hello word!";
    }
}

4、怎么打包?

跟其它 solon 程序一样的方式。具体参考:打包与运行

5、详见示例源码

https://gitee.com/noear/solon-examples/tree/main/1.Solon/demo1092-vertx