package com.fastonetech.balance.controller
import com.fastonetech.vo.AccountVo
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
import java.math.BigDecimal
import java.math.RoundingMode
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.TimeUnit
/**
* @program: balance
* @description: 协程测试
* @author: sunyuhua
* @create: 2021-11-24 10:46
**/
class RunningBankTest {
@Test
fun testRuning(){
val tenantId:Long=1L
val accountVo=runBlocking {
val balanceToValidPeriod =
async { getBalanceAndValidPeriodTimeByTenantId(tenantId) }
//余额
val balance = balanceToValidPeriod.await().first.setScale(2, RoundingMode.FLOOR)
//有效期
val validPeriodTime =
balanceToValidPeriod.await().second.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
//已消费金额
val consumeAmount =
async { getConsumeAmountByTenantId(tenantId).setScale(2, RoundingMode.CEILING) }
//已过期金额
val expireAmount =
async {getExpireAmountByTenantId(tenantId).setScale(2, RoundingMode.CEILING) }
//是否有现金充值(非赠金active-pay的充值)
val isHasCashRecharge =
async { isCashAccount(tenantId) }
AccountVo(balance, validPeriodTime, consumeAmount.await(), expireAmount.await(), isHasCashRecharge.await())
}
//TimeUnit.SECONDS.sleep(3L)
TimeUnit.SECONDS.sleep(10L)
println("sss$accountVo")
}
/**
* 模拟数据库查询计算
*/
private suspend fun getBalanceAndValidPeriodTimeByTenantId(tenantId: Long): Pair<BigDecimal, LocalDateTime> {
delay(5000L)
println("getBalanceAndValidPeriodTimeByTenantId${LocalDateTime.now()}")
return Pair(BigDecimal.valueOf(12.00), LocalDateTime.now())
}
private suspend fun getConsumeAmountByTenantId(tenantId: Long):BigDecimal{
delay(4000L)
println("getConsumeAmountByTenantId${LocalDateTime.now()}")
return BigDecimal.valueOf(100.23)
}
private suspend fun getExpireAmountByTenantId(tenantId: Long):BigDecimal{
delay(3000L)
println("getExpireAmountByTenantId${LocalDateTime.now()}")
return BigDecimal.valueOf(100.23)
}
private suspend fun isCashAccount(tenantId: Long):Boolean{
delay(2000L)
println("isCashAccount${LocalDateTime.now()}")
return false
}
}
执行后的结果为
getBalanceAndValidPeriodTimeByTenantId2021-11-24T11:10:35.525732
isCashAccount2021-11-24T11:10:37.547469100
getExpireAmountByTenantId2021-11-24T11:10:38.544351500
getConsumeAmountByTenantId2021-11-24T11:10:39.555714700
sssAccountVo(balance=12.00, validPeriodTime=2021-11-24 11:10, consumeAmount=100.23, expireAmount=100.23, isHasCashRecharge=false)
协程的怪异问题。暂时留个log,后期需要把协程搞明白再来修改
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sunyuhua_keyboard/article/details/121511294
内容来源于网络,如有侵权,请联系作者删除!