SpringBoot + kotlin 协程小记

前言:

Kotlin 协程是基于 Coroutine 实现的,其设计目的是简化异步编程。协程提供了一种方式,可以在一个线程上写起来像是在多个线程中执行。

协程的基本概念:

  • 协程是轻量级的,不会创建新的线程。

  • 协程会挂起当前的协程,而不会阻塞线程。

  • 协程可以在suspend函数中暂停执行,并在暂停点恢复执行。

一、引包

${kotlin.version} : <kotlin.version>1.8.21</kotlin.version>

注意:org.jetbrains.kotlinx 最新在1.6.0

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-reflect</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlinx</groupId>
            <artifactId>kotlinx-coroutines-core</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-test</artifactId>
            <version>${kotlin.version}</version>
            <scope>test</scope>
        </dependency>

二、 interface 定义

import com.baomidou.mybatisplus.extension.service.IService
import com.zc.bean.PriceBean
import org.springframework.stereotype.Repository

@Repository
interface TestKotlinService : IService<PriceBean> {
    //suspend 协程方法的定义
    suspend fun test(): String
    fun te()
}

三、Ipml 实现

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.zc.bean.PriceBean
import com.zc.mapper.TestKotlinMapper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import lombok.extern.slf4j.Slf4j
import org.springframework.stereotype.Service

/**
 * @author zc
 * @date 2024/4/18 9:56
 * @desc
 */
@Service
@Slf4j
open class TestKotlinServcieImpl : ServiceImpl<TestKotlinMapper, PriceBean>(), TestKotlinService{
    //withContext 切换到指定的线程(IO线程)
    override suspend fun test() = withContext(Dispatchers.IO){
        delay(10000)
        println("suspend")
        return@withContext "success"
    }

    override fun te(){
        println("test")
    }
}

四、controller

/**
 * @author zc
 * @date 2024/4/18 10:38
 * @desc
 */
@RestController
@RequestMapping("/price")
@Tag(name = "kotlin")
class TestKotlinController {

    @Autowired
    private lateinit var testKotlinService: TestKotlinService;

    @GetMapping("test")
    fun testScope(){
        println("start")
        testKotlinService.te()
        //创建协程,并在io线程上执行
        val coroutineScope = CoroutineScope(Dispatchers.IO)
        coroutineScope.launch {
            //async/await获取返回值
//            val result =  async {  testKotlinService.test() }.await()
            val result =
                withContext(Dispatchers.IO) { testKotlinService.test() }
            println("result: $result")
        }
        println("end")
    }
}

五、测试

调用swagger 接口测试,在等待10秒后打印出suspend result: success,异步调用成功

六、学习文档:

文档 · Kotlin 官方文档 中文版

相关推荐
何陈陈1 分钟前
【Linux】线程池
linux·服务器·开发语言·c++
清风玉骨5 分钟前
Qt-QHBoxLayout布局类控件(42)
开发语言·qt
2401_8572979117 分钟前
秋招内推2025-招联金融
java·前端·算法·金融·求职招聘
一 乐21 分钟前
考研论坛平台|考研论坛小程序系统|基于java和微信小程序的考研论坛平台小程序设计与实现(源码+数据库+文档)
java·数据库·学习·考研·微信·小程序·源码
一 乐23 分钟前
租拼车平台|小区租拼车管理|基于java的小区租拼车管理信息系统小程序设计与实现(源码+数据库+文档)
java·数据库·vue.js·微信·notepad++·拼车
夏旭泽25 分钟前
C-include
开发语言·c++
通信仿真实验室27 分钟前
MATLAB使用眼图分析QPSK通信系统接收端匹配滤波后的信号
开发语言·算法·matlab
通信仿真实验室32 分钟前
(15)衰落信道模型作用于信号是相乘还是卷积
开发语言·人工智能·算法·matlab
xmh-sxh-131441 分钟前
如何选择数据库架构
java
jxxchallenger41 分钟前
踩坑spring cloud gateway /actuator/gateway/refresh不生效
java·数据库·gateway