步骤
- 使用idea中的Spring Initializr创建
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bbb5339aa59bf1b954b18172527da5e6.png)
- 创建成功后的目录,可见kotlin目录与启动类。浏览
pom.xml
可见相关kotlin依赖。以及Spring编译插件,使得在kotlin中使用Spring更加方便。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6154be4897c8722b59108262342478ce.png)
- 点击运行,可见控制台显示。程序运行在Tomcat服务器8080端口上。
- 我们来创建一个股票价格类
package com.hx.rest.controller
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Flux
import java.time.Duration
import java.time.LocalDateTime
import java.util.concurrent.ThreadLocalRandom
@RestController
class HelloController{
@RequestMapping(value = ["/price/{symbol}"],produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
fun prices(@PathVariable symbol: String): Flux<StockPrice> {
return Flux.interval(Duration.ofSeconds(1))
.map { StockPrice(symbol,RandomStockPrice(), LocalDateTime.now()) }
}
private fun RandomStockPrice(): Double {
return ThreadLocalRandom.current().nextDouble(100.0)
}
data class StockPrice(val symbol: String,val price:Double,val time:LocalDateTime)
}
- 访问:
http://localhost:8080/price/demo
测试,可见每个一秒,价格更新。