前言
spring官方最近宣布,將在spring framework 5.0版本中正式支持kotlin語言。這意味著spring boot 2.x版本將為kotlin提供一流的支持。
這并不會令人意外,因為pivotal團隊以廣泛接納??jvm語言(如scala和groovy)而聞名。
kotlin 是一個基于 jvm 的編程語言,它的簡潔、便利早已不言而喻。kotlin 能夠勝任 java 做的所有事。目前,我們公司 c 端 的 android 產品全部采用 kotlin 編寫。公司的后端項目也可能會使用 kotlin,所以我給他們做一些 demo 進行演示。
示例一:結合 redis 進行數據存儲和查詢
1.1 配置 gradle
在build.gradle中添加插件和依賴的庫。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
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 // 庫 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 創建 springkotlinapplication:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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會報如下的錯誤:
org.springframework.beans.factory.parsing.beandefinitionparsingexception: configuration problem: @configuration class 'springkotlinapplication' may not be final. remove the final modifier to continue.
因為 kotlin 的類默認是final的,所以這里需要使用open關鍵字。
1.3 配置 redis
在 application.yml 中添加 redis 的配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
spring: redis: #數據庫索引 database: 0 host: 127.0 . 0.1 port: 6379 password: lettuce: pool: #最大連接數 max-active: 8 #最大阻塞等待時間(負數表示沒限制) max-wait: - 1 #最大空閑 max-idle: 8 #最小空閑 min-idle: 0 #連接超時時間 timeout: 10000 |
接下來定義 redis 的序列化器,本文采用fastjson,當然使用gson、jackson等都可以,看個人喜好。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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" ) } } |
創建 redisconfig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
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 創建 service
創建一個 user 對象,使用 datat class 類型。
1
|
data class user(var username:string,var password:string):serializable |
創建操作 user 的service接口
1
2
3
4
5
6
7
8
9
10
11
|
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) } |
創建 service 的實現類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
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 創建 controller
創建一個 usercontroller,包含 createuser、getuser 兩個接口。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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" ) } } |
創建完 controller 之后,可以進行測試了。
創建用戶tony:
查詢用戶tony:
創建用戶monica:
查詢用戶monica:
示例二:結合 rxjava 模擬順序、并發地執行任務
2.1 創建 mocktask
首先定義一個任務接口,所有的任務都需要實現該接口:
1
2
3
4
5
6
7
|
/** * created by tony on 2018/11/13. */ interface itask { fun execute() } |
再創建一個模擬的任務,其中delayinseconds用來模擬任務所花費的時間,單位是秒。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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 創建 concurrenttasksexecutor
順序執行的話比較簡單,一個任務接著一個任務地完成即可,是單線程的操作。
對于并發而言,在這里借助 rxjava 的 merge 操作符來將多個任務進行合并。還用到了 rxjava 的任務調度器 scheduler,createscheduler()是按照所需的線程數來創建scheduler的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
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 創建 controller
創建一個 taskscontroller,包含 sequential、concurrent 兩個接口,會分別把sequential 和 concurrent 執行任務的時間展示出來。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
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) } |
順序地執行多個任務:http://localhost:8080/tasks/sequential?task=1&task=2&task=3&task=4
每個任務所花費的時間分別是1秒、2秒、3秒和4秒。最后,一共花費了10.009秒。
兩個線程并發地執行多個任務:http://localhost:8080/tasks/concurrent?task=1&task=2&task=3&task=4&threads=2
三個線程并發地執行多個任務:http://localhost:8080/tasks/concurrent?task=1&task=2&task=3&task=4&threads=3
總結
本文使用了 kotlin 的特性跟 spring boot 整合進行后端開發。kotlin 的很多語法糖使得開發變得更加便利,當然 kotlin 也是 java 的必要補充。
本文 demo 的 github 地址:https://github.com/fengzhizi715/kotlin-spring-demo
好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://juejin.im/post/5bebb4436fb9a04a072feb74