spring boot与ktor整合的实现方法

作者:猫哥不懂技术 时间:2022-01-18 04:20:19 

背景

在用了一阵子 Ktor 之后,深感基于协程的方便,但是公司的主要技术栈是 SpringBoot,虽然已经整合了 Kotlin,但是如果有 Ktor 加持则会更加的方便。因此作了一番研究后,也完全可以实现这样的整合了。

建立一个 starter

首先新建一个 Kotlin 项目,在其 build.gradle 内加入对 SpringBoot 和 Ktor 的依赖,并同时加入对打为 jar 包的代码:


dependencies {
 implementation "org.springframework.boot:spring-boot-starter-aop:${springBootVersion}"
 implementation "io.ktor:ktor-jackson:${ktorVersion}"
 compile "io.ktor:ktor-server-netty:${ktorVersion}"
 compile "io.ktor:ktor-html-builder:${ktorVersion}"

testImplementation "org.springframework.boot:spring-boot-starter-test:${springBootVersion}"
 testCompile "io.ktor:ktor-client-apache:${ktorVersion}"
 testCompile "io.ktor:ktor-server-test-host:${ktorVersion}"
}

jar {
 from {
   configurations.runtime.collect { zipTree(it) }
 }
}

task sourceJar(type: Jar) {
 from sourceSets.main.allSource
 classifier 'sources'
}

对于 SpringBoot 来说,工程内的 Configuration,Controller,Module 都是必要的,因此也需要 Ktor 可以符合这些约定俗成的组件。

那么就简单来实现一下吧,首先实现 Controller 的代码,我们只需要让 SpringBoot 的 Controller 支持 Ktor 的路由写法就可以了:


interface KRouter {
 fun Routing.route()
}

@ContextDsl
fun Routing.request(
path: String,
body: PipelineInterceptor<Unit, ApplicationCall>
) = route(path) { handle(body) }

然后实现基础的 Module:


interface KModule {

fun Application.defaultRegister(
  useCompress: Boolean = false,
  redirectHttps: Boolean = false,
  headers: String = ""
 ) {
   install(ContentNegotiation) { jackson { } }
   install(PartialContent) { maxRangeCount = 10 }
   if (useCompress) {
     install(Compression) {
       gzip { priority = 1.0 }
       deflate {
         priority = 10.0
         minimumSize(1024)
       }
     }
   }
   if (redirectHttps) {
     install(HttpsRedirect) {
       sslPort = URLProtocol.HTTPS.defaultPort
       permanentRedirect = true
     }
   }
   if (headers != "") {
     install(DefaultHeaders) {
       headers.toCookieMap().forEach { (t, u) -> header(t, "$u") }
     }
   }
 }

@ContextDsl
 fun Application.register()
}

在这个 Module 内,defaultRegister 是通过读取 application.yml 内的配置的参数来决定的,register 是用来让用户覆盖,并实现额外的模块注册。

最后只需要实现 Configuration 就可以了,这里实现读取 yml 并且调用 defaultRegister 等方法:


/**
* spring.ktor 配置项
* @param host 服务器主机名
* @param port 绑定端口
* @param compress 是否启用压缩
* @param redirectHttps 是否自动重定向到 https
* @param headers 默认的请求头
*/
@ConfigurationProperties(prefix = "spring.ktor")
open class KProperties(
   open var host: String = "0.0.0.0",
   open var port: Int = 8080,
   open var compress: Boolean = false,
   open var redirectHttps: Boolean = false,
   open var headers: String = ""
)

用这个类来映射 yml 内的配置,并且在取值后即可实现对模块,路由等的初始化:


@Configuration
@EnableConfigurationProperties(KProperties::class)
open class KConfiguration {

@Resource
 private lateinit var properties: KProperties

@Bean
 @ConditionalOnMissingBean
 open fun engineFactory() = Netty

@Bean
 @ConditionalOnMissingBean
 open fun applicationEngine(
  engineFactory: ApplicationEngineFactory<ApplicationEngine, out ApplicationEngine.Configuration>,
  context: ApplicationContext
 ): ApplicationEngine {
   return embeddedServer(engineFactory, host = properties.host, port = properties.port) {
     val modules = context.getBeansOfType(KModule::class.java).values
     val routes = context.getBeansOfType(KRouter::class.java).values
     modules.forEach { it.apply {
       defaultRegister(
         useCompress = properties.compress,
         redirectHttps = properties.redirectHttps,
         headers = properties.headers)
       register()
     } }
     routing { routes.forEach { it.apply { route() } } }
   }.start()
 }

@Bean
 @ConditionalOnMissingBean
 open fun application(
   applicationEngine: ApplicationEngine,
   context: ApplicationContext
 ): Application = applicationEngine.environment.application
}

来源:https://rarnu.xyz/archives/实现springboot与ktor的整合

标签:springboot,整合,ktor
0
投稿

猜你喜欢

  • Android jni调试打印char阵列的实例详解

    2022-06-18 14:55:40
  • 解决BigDecimal转long丢失精度的问题

    2022-07-16 13:44:22
  • SpringBoot整合JDBC、Druid数据源的示例代码

    2022-06-19 20:44:24
  • Java Socket使用加密协议进行传输对象的方法

    2023-11-28 12:47:44
  • 必须要学会的JMM与volatile

    2021-07-30 14:07:53
  • activemq整合springboot使用方法(个人微信小程序用)

    2023-07-08 22:29:55
  • SpringBoot项目为何引入大量的starter?如何自定义starter?

    2022-12-28 21:39:02
  • 基于Java8实现提高Excel读写效率

    2023-11-25 10:01:37
  • java实现字符串四则运算公式解析工具类的方法

    2021-11-03 09:22:23
  • Spring Shell应用程序开发流程解析

    2021-06-28 23:20:50
  • android开发之Json文件的读写的示例代码

    2021-12-02 11:55:18
  • Hibernate多对一单项关联

    2023-05-10 18:16:11
  • 总结Java集合类操作优化经验

    2023-01-27 10:29:37
  • Spring@Value使用获取配置信息为null的操作

    2021-08-01 23:46:27
  • IDEA插件EasyCode及MyBatis最优配置步骤详解

    2023-11-09 03:19:19
  • springmvc请求转发和重定向问题(携带参数和不携带参数)

    2022-09-17 13:53:59
  • 详解Java图形化编程中的鼠标事件设计

    2022-07-11 08:11:31
  • Struts2源码分析之ParametersInterceptor拦截器

    2023-11-05 00:41:37
  • 解决线程池中ThreadGroup的坑

    2023-08-24 00:13:47
  • Java日常练习题,每天进步一点点(40)

    2022-12-20 14:39:53
  • asp之家 软件编程 m.aspxhome.com