利用Kotlin + Spring Boot實(shí)現(xiàn)后端開(kāi)發(fā)
前言
Spring官方最近宣布,將在Spring Framework 5.0版本中正式支持Kotlin語(yǔ)言。這意味著Spring Boot 2.x版本將為Kotlin提供一流的支持。
這并不會(huì)令人意外,因?yàn)镻ivotal團(tuán)隊(duì)以廣泛接納JVM語(yǔ)言(如Scala和Groovy)而聞名。
Kotlin 是一個(gè)基于 JVM 的編程語(yǔ)言,它的簡(jiǎn)潔、便利早已不言而喻。Kotlin 能夠勝任 Java 做的所有事。目前,我們公司 C 端 的 Android 產(chǎn)品全部采用 Kotlin 編寫(xiě)。公司的后端項(xiàng)目也可能會(huì)使用 Kotlin,所以我給他們做一些 demo 進(jìn)行演示。
示例一:結(jié)合 Redis 進(jìn)行數(shù)據(jù)存儲(chǔ)和查詢
1.1 配置 gradle
在build.gradle中添加插件和依賴的庫(kù)。
plugins { id 'java' id 'org.jetbrains.kotlin.jvm' version '1.3.0' } ext { libraries = [ rxjava : "2.2.2", logback : "1.2.3", spring_boot : "2.1.0.RELEASE", commons_pool2 : "2.6.0", fastjson : "1.2.51" ] } group 'com.kotlin.tutorial' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 def libs = rootProject.ext.libraries // 庫(kù) repositories { mavenCentral() } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8" compile "org.jetbrains.kotlin:kotlin-reflect:1.3.0" testCompile group: 'junit', name: 'junit', version: '4.12' implementation "io.reactivex.rxjava2:rxjava:${libs.rxjava}" implementation "ch.qos.logback:logback-classic:${libs.logback}" implementation "ch.qos.logback:logback-core:${libs.logback}" implementation "ch.qos.logback:logback-access:${libs.logback}" implementation "org.springframework.boot:spring-boot-starter-web:${libs.spring_boot}" implementation "org.springframework.boot:spring-boot-starter-data-redis:${libs.spring_boot}" implementation "org.apache.commons:commons-pool2:${libs.commons_pool2}" implementation "com.alibaba:fastjson:${libs.fastjson}" } compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
1.2 創(chuàng)建 SpringKotlinApplication:
import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication /** * Created by tony on 2018/11/13. */ @SpringBootApplication open class SpringKotlinApplication fun main(args: Array<String>) { SpringApplication.run(SpringKotlinApplication::class.java, *args) }
需要注意open的使用,如果不加open會(huì)報(bào)如下的錯(cuò)誤:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: @Configuration class 'SpringKotlinApplication' may not be final. Remove the final modifier to continue.
因?yàn)?Kotlin 的類默認(rèn)是final的,所以這里需要使用open關(guān)鍵字。
1.3 配置 redis
在 application.yml 中添加 redis 的配置
spring: redis: #數(shù)據(jù)庫(kù)索引 database: 0 host: 127.0.0.1 port: 6379 password: lettuce: pool: #最大連接數(shù) max-active: 8 #最大阻塞等待時(shí)間(負(fù)數(shù)表示沒(méi)限制) max-wait: -1 #最大空閑 max-idle: 8 #最小空閑 min-idle: 0 #連接超時(shí)時(shí)間 timeout: 10000
接下來(lái)定義 redis 的序列化器,本文采用fastjson,當(dāng)然使用gson、jackson等都可以,看個(gè)人喜好。
import com.alibaba.fastjson.JSON import com.alibaba.fastjson.serializer.SerializerFeature import org.springframework.data.redis.serializer.RedisSerializer import org.springframework.data.redis.serializer.SerializationException import java.nio.charset.Charset /** * Created by tony on 2018/11/13. */ class FastJsonRedisSerializer<T>(private val clazz: Class<T>) : RedisSerializer<T> { @Throws(SerializationException::class) override fun serialize(t: T?) = if (null == t) { ByteArray(0) } else JSON.toJSONString(t, SerializerFeature.WriteClassName).toByteArray(DEFAULT_CHARSET) @Throws(SerializationException::class) override fun deserialize(bytes: ByteArray?): T? { if (null == bytes || bytes.size <= 0) { return null } val str = String(bytes, DEFAULT_CHARSET) return JSON.parseObject(str, clazz) as T } companion object { private val DEFAULT_CHARSET = Charset.forName("UTF-8") } }
創(chuàng)建 RedisConfig
import org.springframework.data.redis.core.RedisTemplate import org.springframework.data.redis.connection.RedisConnectionFactory import org.springframework.context.annotation.Bean import org.springframework.data.redis.cache.RedisCacheManager import org.springframework.cache.CacheManager import org.springframework.cache.annotation.CachingConfigurerSupport import org.springframework.cache.annotation.EnableCaching import org.springframework.context.annotation.Configuration import org.springframework.data.redis.serializer.StringRedisSerializer import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.data.redis.core.RedisOperations import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.autoconfigure.data.redis.RedisProperties /** * Created by tony on 2018/11/13. */ @EnableCaching @Configuration @ConditionalOnClass(RedisOperations::class) @EnableConfigurationProperties(RedisProperties::class) open class RedisConfig : CachingConfigurerSupport() { @Bean(name = arrayOf("redisTemplate")) @ConditionalOnMissingBean(name = arrayOf("redisTemplate")) open fun redisTemplate(redisConnectionFactory: RedisConnectionFactory): RedisTemplate<Any, Any> { val template = RedisTemplate<Any, Any>() val fastJsonRedisSerializer = FastJsonRedisSerializer(Any::class.java) template.valueSerializer = fastJsonRedisSerializer template.hashValueSerializer = fastJsonRedisSerializer template.keySerializer = StringRedisSerializer() template.hashKeySerializer = StringRedisSerializer() template.connectionFactory = redisConnectionFactory return template } //緩存管理器 @Bean open fun cacheManager(redisConnectionFactory: RedisConnectionFactory): CacheManager { val builder = RedisCacheManager .RedisCacheManagerBuilder .fromConnectionFactory(redisConnectionFactory) return builder.build() } }
這里也都需要使用open,理由同上。
1.4 創(chuàng)建 Service
創(chuàng)建一個(gè) User 對(duì)象,使用 datat class 類型。
data class User(var userName:String,var password:String):Serializable
創(chuàng)建操作 User 的Service接口
import com.kotlin.tutorial.user.User /** * Created by tony on 2018/11/13. */ interface IUserService { fun getUser(username: String): User fun createUser(username: String,password: String) }
創(chuàng)建 Service 的實(shí)現(xiàn)類:
import com.kotlin.tutorial.user.User import com.kotlin.tutorial.user.service.IUserService import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.redis.core.RedisTemplate import org.springframework.stereotype.Service /** * Created by tony on 2018/11/13. */ @Service class UserServiceImpl : IUserService { @Autowired lateinit var redisTemplate: RedisTemplate<Any, Any> override fun getUser(username: String): User { var user = redisTemplate.opsForValue().get("user_${username}") if (user == null) { user = User("default","000000") } return user as User } override fun createUser(username: String, password: String) { redisTemplate.opsForValue().set("user_${username}", User(username, password)) } }
1.5 創(chuàng)建 Controller
創(chuàng)建一個(gè) UserController,包含 createUser、getUser 兩個(gè)接口。
import com.kotlin.tutorial.user.User import com.kotlin.tutorial.user.service.IUserService import com.kotlin.tutorial.web.dto.HttpResponse import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController /** * Created by tony on 2018/11/13. */ @RestController @RequestMapping("/user") class UserController { @Autowired lateinit var userService: IUserService @GetMapping("/getUser") fun getUser(@RequestParam("name") userName: String): HttpResponse<User> { return HttpResponse(userService.getUser(userName)) } @GetMapping("/createUser") fun createUser(@RequestParam("name") userName: String,@RequestParam("password") password: String): HttpResponse<String> { userService.createUser(userName,password) return HttpResponse("create ${userName} success") } }
創(chuàng)建完 Controller 之后,可以進(jìn)行測(cè)試了。
創(chuàng)建用戶tony:
查詢用戶tony:
創(chuàng)建用戶monica:
查詢用戶monica:
示例二:結(jié)合 RxJava 模擬順序、并發(fā)地執(zhí)行任務(wù)
2.1 創(chuàng)建 MockTask
首先定義一個(gè)任務(wù)接口,所有的任務(wù)都需要實(shí)現(xiàn)該接口:
/** * Created by tony on 2018/11/13. */ interface ITask { fun execute() }
再創(chuàng)建一個(gè)模擬的任務(wù),其中delayInSeconds用來(lái)模擬任務(wù)所花費(fèi)的時(shí)間,單位是秒。
import java.util.concurrent.TimeUnit import com.kotlin.tutorial.task.ITask /** * Created by tony on 2018/11/13. */ class MockTask(private val delayInSeconds: Int) : ITask { /** * Stores information if task was started. */ var started: Boolean = false /** * Stores information if task was successfully finished. */ var finishedSuccessfully: Boolean = false /** * Stores information if the task was interrupted. * It can happen if the thread that is running this task was killed. */ var interrupted: Boolean = false /** * Stores the thread identifier in which the task was executed. */ var threadId: Long = 0 override fun execute() { try { this.threadId = Thread.currentThread().id this.started = true TimeUnit.SECONDS.sleep(delayInSeconds.toLong()) this.finishedSuccessfully = true } catch (e: InterruptedException) { this.interrupted = true } } }
2.2 創(chuàng)建 ConcurrentTasksExecutor
順序執(zhí)行的話比較簡(jiǎn)單,一個(gè)任務(wù)接著一個(gè)任務(wù)地完成即可,是單線程的操作。
對(duì)于并發(fā)而言,在這里借助 RxJava 的 merge 操作符來(lái)將多個(gè)任務(wù)進(jìn)行合并。還用到了 RxJava 的任務(wù)調(diào)度器 Scheduler,createScheduler()是按照所需的線程數(shù)來(lái)創(chuàng)建Scheduler的。
import com.kotlin.tutorial.task.ITask import io.reactivex.Completable import io.reactivex.schedulers.Schedulers import org.slf4j.LoggerFactory import org.springframework.util.CollectionUtils import java.util.* import java.util.concurrent.Executors import java.util.stream.Collectors /** * Created by tony on 2018/11/13. */ class ConcurrentTasksExecutor(private val numberOfConcurrentThreads: Int, private val tasks: Collection<ITask>?) : ITask { val log = LoggerFactory.getLogger(this.javaClass) constructor(numberOfConcurrentThreads: Int, vararg tasks: ITask) : this(numberOfConcurrentThreads, if (tasks == null) null else Arrays.asList<ITask>(*tasks)) {} init { if (numberOfConcurrentThreads < 0) { throw RuntimeException("Amount of threads must be higher than zero.") } } /** * Converts collection of tasks (except null tasks) to collection of completable actions. * Each action will be executed in thread according to the scheduler created with [.createScheduler] method. * * @return list of completable actions */ private val asConcurrentTasks: List<Completable> get() { if (tasks!=null) { val scheduler = createScheduler() return tasks.stream() .filter { task -> task != null } .map { task -> Completable .fromAction { task.execute() } .subscribeOn(scheduler) } .collect(Collectors.toList()) } else { return ArrayList<Completable>() } } /** * Checks whether tasks collection is empty. * * @return true if tasks collection is null or empty, false otherwise */ private val isTasksCollectionEmpty: Boolean get() = CollectionUtils.isEmpty(tasks) /** * Executes all tasks concurrent way only if collection of tasks is not empty. * Method completes when all of the tasks complete (or one of them fails). * If one of the tasks failed the the exception will be rethrown so that it can be handled by mechanism that calls this method. */ override fun execute() { if (isTasksCollectionEmpty) { log.warn("There are no tasks to be executed.") return } log.debug("Executing #{} tasks concurrent way.", tasks?.size) Completable.merge(asConcurrentTasks).blockingAwait() } /** * Creates a scheduler that will be used for executing tasks concurrent way. * Scheduler will use number of threads defined in [.numberOfConcurrentThreads] * * @return scheduler */ private fun createScheduler() = Schedulers.from(Executors.newFixedThreadPool(numberOfConcurrentThreads)) }
2.3 創(chuàng)建 Controller
創(chuàng)建一個(gè) TasksController,包含 sequential、concurrent 兩個(gè)接口,會(huì)分別把sequential 和 concurrent 執(zhí)行任務(wù)的時(shí)間展示出來(lái)。
import com.kotlin.tutorial.task.impl.ConcurrentTasksExecutor import com.kotlin.tutorial.task.impl.MockTask import com.kotlin.tutorial.web.dto.TaskResponse import com.kotlin.tutorial.web.dto.ErrorResponse import com.kotlin.tutorial.web.dto.HttpResponse import org.springframework.http.HttpStatus import org.springframework.util.StopWatch import org.springframework.web.bind.annotation.* import java.util.stream.Collectors import java.util.stream.IntStream /** * Created by tony on 2018/11/13. */ @RestController @RequestMapping("/tasks") class TasksController { @GetMapping("/sequential") fun sequential(@RequestParam("task") taskDelaysInSeconds: IntArray): HttpResponse<TaskResponse> { val watch = StopWatch() watch.start() IntStream.of(*taskDelaysInSeconds) .mapToObj{ MockTask(it) } .forEach{ it.execute() } watch.stop() return HttpResponse(TaskResponse(watch.totalTimeSeconds)) } @GetMapping("/concurrent") fun concurrent(@RequestParam("task") taskDelaysInSeconds: IntArray, @RequestParam("threads",required = false,defaultValue = "1") numberOfConcurrentThreads: Int): HttpResponse<TaskResponse> { val watch = StopWatch() watch.start() val delayedTasks = IntStream.of(*taskDelaysInSeconds) .mapToObj{ MockTask(it) } .collect(Collectors.toList()) ConcurrentTasksExecutor(numberOfConcurrentThreads, delayedTasks).execute() watch.stop() return HttpResponse(TaskResponse(watch.totalTimeSeconds)) } @ExceptionHandler(IllegalArgumentException::class) @ResponseStatus(HttpStatus.BAD_REQUEST) fun handleException(e: IllegalArgumentException) = ErrorResponse(e.message) }
順序地執(zhí)行多個(gè)任務(wù):http://localhost:8080/tasks/sequential?task=1&task=2&task=3&task=4
每個(gè)任務(wù)所花費(fèi)的時(shí)間分別是1秒、2秒、3秒和4秒。最后,一共花費(fèi)了10.009秒。
兩個(gè)線程并發(fā)地執(zhí)行多個(gè)任務(wù):http://localhost:8080/tasks/concurrent?task=1&task=2&task=3&task=4&threads=2
三個(gè)線程并發(fā)地執(zhí)行多個(gè)任務(wù):http://localhost:8080/tasks/concurrent?task=1&task=2&task=3&task=4&threads=3
總結(jié)
本文使用了 Kotlin 的特性跟 Spring Boot 整合進(jìn)行后端開(kāi)發(fā)。Kotlin 的很多語(yǔ)法糖使得開(kāi)發(fā)變得更加便利,當(dāng)然 Kotlin 也是 Java 的必要補(bǔ)充。
本文 demo 的 github 地址:https://github.com/fengzhizi715/kotlin-spring-demo
好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- SpringMVC前端和后端數(shù)據(jù)交互總結(jié)
- java web SpringMVC后端傳json數(shù)據(jù)到前端頁(yè)面實(shí)例代碼
- Spring MVC前端與后端5種ajax交互方法【總結(jié)】
- Spring MVC前后端的數(shù)據(jù)傳輸?shù)膶?shí)現(xiàn)方法
- 輕松玩轉(zhuǎn)BootstrapTable(后端使用SpringMVC+Hibernate)
- laypage+SpringMVC實(shí)現(xiàn)后端分頁(yè)
- Spring boot + thymeleaf 后端直接給onclick函數(shù)賦值的實(shí)現(xiàn)代碼
- spring boot+vue 的前后端分離與合并方案實(shí)例詳解
- Spring Boot + Vue 前后端分離開(kāi)發(fā)之前端網(wǎng)絡(luò)請(qǐng)求封裝與配置
- spring mvc 實(shí)現(xiàn)獲取后端傳遞的值操作示例
相關(guān)文章
SpringBoot注解@ConditionalOnClass底層源碼實(shí)現(xiàn)
這篇文章主要為大家介紹了SpringBoot注解@ConditionalOnClass底層源碼實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02spring cloud升級(jí)到spring boot 2.x/Finchley.RELEASE遇到的坑
這篇文章主要介紹了spring cloud升級(jí)到spring boot 2.x/Finchley.RELEASE遇到的坑,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08java如何實(shí)現(xiàn)多線程的順序執(zhí)行
多線程是java的一種重要技術(shù),但是多線程的運(yùn)行是沒(méi)有絕對(duì)的順序的,那么java如何實(shí)現(xiàn)多線程的順序執(zhí)行,下面就一起來(lái)了解一下2021-05-05SpringBoot中JPA實(shí)現(xiàn)Sort排序的三種方式小結(jié)
這篇文章主要介紹了SpringBoot中JPA實(shí)現(xiàn)Sort排序的三種方式小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11Spring定時(shí)任務(wù)中@PostConstruct被多次執(zhí)行異常的分析與解決
這篇文章主要給大家介紹了關(guān)于Spring定時(shí)任務(wù)中@PostConstruct被多次執(zhí)行異常的分析與解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10java+selenium實(shí)現(xiàn)滑塊驗(yàn)證
現(xiàn)在越來(lái)越多的網(wǎng)站都使用采用滑塊驗(yàn)證來(lái)作為驗(yàn)證機(jī)制,用于判斷用戶是否為人類而不是機(jī)器人,本文就將利用java和selenium實(shí)現(xiàn)滑塊驗(yàn)證,希望對(duì)大家有所幫助2023-12-12基于SpringMVC接受JSON參數(shù)詳解及常見(jiàn)錯(cuò)誤總結(jié)
下面小編就為大家分享一篇基于SpringMVC接受JSON參數(shù)詳解及常見(jiàn)錯(cuò)誤總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-03-03Java實(shí)現(xiàn)的動(dòng)態(tài)數(shù)字時(shí)鐘功能示例【顯示世界時(shí)間】
這篇文章主要介紹了Java實(shí)現(xiàn)的動(dòng)態(tài)數(shù)字時(shí)鐘功能,結(jié)合實(shí)例形式分析了java顯示北京、紐約、倫敦等世界時(shí)間的相關(guān)日期時(shí)間運(yùn)算操作技巧,需要的朋友可以參考下2019-03-03