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

相关推荐
جيون داد ناالام ميづ43 分钟前
七、MyBatis 源码剖析:核心流程拆解(初始化 + SQL 执行)
java·sql·mybatis
ClkLog-开源埋点用户分析1 小时前
【产品说明】【埋点分析】ClkLog 商业版 Java 运行环境安全更新说明
java·开发语言
秋饼1 小时前
Spring Framework 7 内置弹性实战:@Retryable 语义翻转、虚拟线程流量放大与 LLM 网关治理
java·ai·技术分享·后端开发
RuoyiOffice1 小时前
Flowable只是起点:一套OA背后的单据、资源与协作设计
java·vue.js·spring boot·flowable·企业管理·oa·ruoyi office
yuzhiboyouye2 小时前
《阿里巴巴 Java 开发手册》的 MySQL 核心规范
java·开发语言·mysql
郝学胜-神的一滴2 小时前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
geovindu2 小时前
python: KNeighborsClassifier K
开发语言·后端·python·算法
秋饼3 小时前
Spring AI 2.0 渐进式工具披露实战:ToolSearchToolCallingAdvisor 源码机制、四种 ToolIndex 选型与多租户踩坑
java·ai·技术分享·后端开发
时间的情敌4 小时前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
Amumu121385 小时前
TypeScript学习: 基本类型(一)
开发语言·前端·typescript