nats api gateway 基于spring boot 实现的一个思路

以前简单说过,方法实际比较多,一种是直接提供一个比较明确的rest controller,按照服务格式约定,处理数据,还有一种方法就是动态注册controller 服务(可以更加精细的生成rest api),同时如果有openapi 文档需求的,可以动态注册文档api

参考示例

只提供简单演示,具体的后续有时间了提供更加清晰的说明

  • 动态注册api
@Bean
CommandLineRunner runner(RequestMappingHandlerMapping requestMappingHandlerMapping,DemoApi demoApi) {

    return args -> {
        System.out.println("Registered Endpoints:");
        RequestMappingInfo mapping = RequestMappingInfo
                .paths("/dynamic")
                .methods(RequestMethod.POST)
                .build();
        Method handlerMethod = demoApi.getClass().getMethod("demo");
        requestMappingHandlerMapping.registerMapping(mapping, demoApi, handlerMethod);

    };
}
  • 动态注册文档api

基于了springdoc的

SpringDocUtils.getConfig().addRestControllers(DemoApi.class);

内部实现机制

就是通过上边的示例,可以结合自定义注解(比如我们自己提供一个rest api 的定义,可以方便暴露api),进行api 的动态注册,对于内部请求的处理可以只提供一个统一的服务bean 就可以,当然动态注册也是可以的,将nats service handler 注册为bean,包含rest 注解,之后就可以方便的同时暴露rest api 了,实现起来也比较简单

参考资料

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.html

https://github.com/spring-projects/spring-framework/blob/main/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java

https://www.baeldung.com/spring-mvc-handler-adapters

posted on 2026-01-13 08:00  荣锋亮  阅读(2)  评论(0)    收藏  举报

导航