spring boot与ktor整合的实现方法
作者:猫哥不懂技术 发布时间:2022-01-18 04:20:19
标签:springboot,整合,ktor
背景
在用了一阵子 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的整合


猜你喜欢
- 本文实例讲述了WinForm通过操作注册表实现限制软件使用次数的方法。分享给大家供大家参考,具体如下:1.创建注册表文件:打开记事本,输入一
- Bat.aspx: 程序代码 <%@ Page Language="C#" AutoEventWireu
- java进行时间转换成unix timestamp的具体代码,供大家参考,具体内容如下import java.text.DateFormat
- 一、Spring Boot 、 Spring MVC 、Spring对比首先你需要明白一件事情:Spring Boot项目目的并不是替换Sp
- 写在前面在这里,我们将会学习怎么利用java8 快速的打印出需要打印的元素利用stream打印元素在Java中,有三种不同的方法来打印Jav
- public class MenuEx extends Activity { private static final String TAG
- 编写C#程序的时候,我们都遇到过配置文件,而如今绝大多数的配置文件都是用XML写的。所以在处理的时候就需要操作XML文件。那么C#如何操作X
- 本文以实例讲述了android中DatePicker和TimePicker的使用方法,具体步骤如下:下面是实现具体功能的代码,其中main.
- spring boot与profilespring boot 的项目中不再使用xml的方式进行配置,并且,它还遵循着约定大于配置。静态获取方
- 本文实例讲述了Android编程开发之ScrollView嵌套GridView的方法。分享给大家供大家参考,具体如下:前些日子在开发中用到了
- 写在前面本文讲解的是 SpringBoot 引入容器化技术 Docker 实现一次构建到处运行,包括镜像构建、Docker仓库搭建使用、Do
- 本文实例讲述了Java抽象类和抽象方法定义与用法。分享给大家供大家参考,具体如下:一、Java抽象类参考资料:Java抽象类 详解1、抽象类
- springboot创建线程池两种方式1.使用static代码块创建这样的方式创建的好处是当代码用到线程池的时候才会初始化核心线程数具体代码
- 本文实例讲述了C#自定义繁体和简体字库实现中文繁体和简体之间转换的方法。分享给大家供大家参考。具体分析如下:这里使用C#自定义繁体和简体字库
- 在Unity中实现简单的伪时间同步,只是读取数据库所在电脑的当前时间using UnityEngine;using System.Colle
- 在第一次启动项目的时候,由于使用了RabbitMQ的默认guest账号,怎么也登不进去,后来还是在Admin重新创建了一个其他的账号,然后开
- private void txtBarCode_KeyPress(object sender, KeyPressEventArg
- /// <summary> /// 安装的excel的版本,0为没有安装,大于1说明安装了多个. /// </summar
- 利用Java,在控制台操作下,编写的五子棋,作为复习二维数组,面向对象等基础知识。w表示白棋,b表示黑棋import java.util.S
- C#学习笔记- 浅谈数组复制,排序,取段,元组using System;using System.Collections.Generic;n