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 官方文档 中文版

相关推荐
小羊没烦恼!4 小时前
T-SQL查询进阶--理解SQL SERVER中的分区表
服务器·开发语言·前端·javascript·html
小蒜学长4 小时前
微信小程序-高校自习室管理系统(代码+数据库+LW)
java·spring boot·后端·微信小程序·自习室管理
鸥梨菌Honevid5 小时前
UVM 中 REQ 和 RSP 类型详解:从通信模型到 item_done 与 put_response
java·前端·servlet
爱吃香菜的初学者5 小时前
十六.Linux——多线程(2)
linux·运维·开发语言
瑞克-桑切斯5 小时前
真实企业场景 运维安全与管理
java·网络·github
jeo陽5 小时前
04-循环实战:素数、最大公约数、级数求和与枚举法
c语言·开发语言·数据结构
老板一杯拿铁5 小时前
Java 八股文面试详解:从基础到进阶的全面梳理
java·面试
const_qiu5 小时前
第 2.5 章 2.5.4-2.5.5:JWT 双 Token 与声明式权限守卫
java·人工智能
暖核5 小时前
kubeadm 集群运维:Worker 节点下线删除、整套集群销毁重建指南
运维·开发语言·php
bug菌5 小时前
一个周末就想把短链服务推到 10 万 QPS,真能靠加 Redis 做到吗?
java·redis·go