经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
利用Kotlin + Spring Boot实现后端开发
来源:jb51  时间:2018/11/15 10:06:09  对本文有异议

前言

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. plugins {
  2. id 'java'
  3. id 'org.jetbrains.kotlin.jvm' version '1.3.0'
  4. }
  5.  
  6. ext {
  7. libraries = [
  8.  
  9. rxjava : "2.2.2",
  10.  
  11. logback : "1.2.3",
  12.  
  13. spring_boot : "2.1.0.RELEASE",
  14.  
  15. commons_pool2 : "2.6.0",
  16.  
  17. fastjson : "1.2.51"
  18. ]
  19. }
  20.  
  21. group 'com.kotlin.tutorial'
  22. version '1.0-SNAPSHOT'
  23.  
  24. sourceCompatibility = 1.8
  25.  
  26. def libs = rootProject.ext.libraries // 库
  27.  
  28. repositories {
  29. mavenCentral()
  30. }
  31.  
  32. dependencies {
  33. compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
  34. compile "org.jetbrains.kotlin:kotlin-reflect:1.3.0"
  35. testCompile group: 'junit', name: 'junit', version: '4.12'
  36.  
  37. implementation "io.reactivex.rxjava2:rxjava:${libs.rxjava}"
  38.  
  39. implementation "ch.qos.logback:logback-classic:${libs.logback}"
  40. implementation "ch.qos.logback:logback-core:${libs.logback}"
  41. implementation "ch.qos.logback:logback-access:${libs.logback}"
  42.  
  43. implementation "org.springframework.boot:spring-boot-starter-web:${libs.spring_boot}"
  44. implementation "org.springframework.boot:spring-boot-starter-data-redis:${libs.spring_boot}"
  45. implementation "org.apache.commons:commons-pool2:${libs.commons_pool2}"
  46. implementation "com.alibaba:fastjson:${libs.fastjson}"
  47. }
  48.  
  49. compileKotlin {
  50. kotlinOptions.jvmTarget = "1.8"
  51. }
  52. compileTestKotlin {
  53. kotlinOptions.jvmTarget = "1.8"
  54. }

1.2 创建 SpringKotlinApplication:

  1. import org.springframework.boot.SpringApplication
  2. import org.springframework.boot.autoconfigure.SpringBootApplication
  3.  
  4.  
  5. /**
  6. * Created by tony on 2018/11/13.
  7. */
  8. @SpringBootApplication
  9. open class SpringKotlinApplication
  10.  
  11. fun main(args: Array<String>) {
  12. SpringApplication.run(SpringKotlinApplication::class.java, *args)
  13. }

需要注意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. spring:
  2. redis:
  3. #数据库索引
  4. database: 0
  5. host: 127.0.0.1
  6. port: 6379
  7. password:
  8. lettuce:
  9. pool:
  10. #最大连接数
  11. max-active: 8
  12. #最大阻塞等待时间(负数表示没限制)
  13. max-wait: -1
  14. #最大空闲
  15. max-idle: 8
  16. #最小空闲
  17. min-idle: 0
  18. #连接超时时间
  19. timeout: 10000

接下来定义 redis 的序列化器,本文采用fastjson,当然使用gson、jackson等都可以,看个人喜好。

  1. import com.alibaba.fastjson.JSON
  2. import com.alibaba.fastjson.serializer.SerializerFeature
  3. import org.springframework.data.redis.serializer.RedisSerializer
  4. import org.springframework.data.redis.serializer.SerializationException
  5. import java.nio.charset.Charset
  6.  
  7. /**
  8. * Created by tony on 2018/11/13.
  9. */
  10.  
  11. class FastJsonRedisSerializer<T>(private val clazz: Class<T>) : RedisSerializer<T> {
  12.  
  13. @Throws(SerializationException::class)
  14. override fun serialize(t: T?) = if (null == t) {
  15. ByteArray(0)
  16. } else JSON.toJSONString(t, SerializerFeature.WriteClassName).toByteArray(DEFAULT_CHARSET)
  17.  
  18. @Throws(SerializationException::class)
  19. override fun deserialize(bytes: ByteArray?): T? {
  20.  
  21. if (null == bytes || bytes.size <= 0) {
  22. return null
  23. }
  24. val str = String(bytes, DEFAULT_CHARSET)
  25. return JSON.parseObject(str, clazz) as T
  26. }
  27.  
  28. companion object {
  29. private val DEFAULT_CHARSET = Charset.forName("UTF-8")
  30. }
  31. }

创建 RedisConfig

  1. import org.springframework.data.redis.core.RedisTemplate
  2. import org.springframework.data.redis.connection.RedisConnectionFactory
  3. import org.springframework.context.annotation.Bean
  4. import org.springframework.data.redis.cache.RedisCacheManager
  5. import org.springframework.cache.CacheManager
  6. import org.springframework.cache.annotation.CachingConfigurerSupport
  7. import org.springframework.cache.annotation.EnableCaching
  8. import org.springframework.context.annotation.Configuration
  9. import org.springframework.data.redis.serializer.StringRedisSerializer
  10. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
  11. import org.springframework.boot.context.properties.EnableConfigurationProperties
  12. import org.springframework.data.redis.core.RedisOperations
  13. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
  14. import org.springframework.boot.autoconfigure.data.redis.RedisProperties
  15.  
  16.  
  17. /**
  18. * Created by tony on 2018/11/13.
  19. */
  20.  
  21. @EnableCaching
  22. @Configuration
  23. @ConditionalOnClass(RedisOperations::class)
  24. @EnableConfigurationProperties(RedisProperties::class)
  25. open class RedisConfig : CachingConfigurerSupport() {
  26.  
  27. @Bean(name = arrayOf("redisTemplate"))
  28. @ConditionalOnMissingBean(name = arrayOf("redisTemplate"))
  29. open fun redisTemplate(redisConnectionFactory: RedisConnectionFactory): RedisTemplate<Any, Any> {
  30.  
  31. val template = RedisTemplate<Any, Any>()
  32.  
  33. val fastJsonRedisSerializer = FastJsonRedisSerializer(Any::class.java)
  34.  
  35. template.valueSerializer = fastJsonRedisSerializer
  36. template.hashValueSerializer = fastJsonRedisSerializer
  37.  
  38. template.keySerializer = StringRedisSerializer()
  39. template.hashKeySerializer = StringRedisSerializer()
  40.  
  41. template.connectionFactory = redisConnectionFactory
  42. return template
  43. }
  44.  
  45. //缓存管理器
  46. @Bean
  47. open fun cacheManager(redisConnectionFactory: RedisConnectionFactory): CacheManager {
  48. val builder = RedisCacheManager
  49. .RedisCacheManagerBuilder
  50. .fromConnectionFactory(redisConnectionFactory)
  51. return builder.build()
  52. }
  53.  
  54. }

这里也都需要使用open,理由同上。

1.4 创建 Service

创建一个 User 对象,使用 datat class 类型。

  1. data class User(var userName:String,var password:String):Serializable

创建操作 User 的Service接口

  1. import com.kotlin.tutorial.user.User
  2.  
  3. /**
  4. * Created by tony on 2018/11/13.
  5. */
  6. interface IUserService {
  7.  
  8. fun getUser(username: String): User
  9.  
  10. fun createUser(username: String,password: String)
  11. }

创建 Service 的实现类:

  1. import com.kotlin.tutorial.user.User
  2. import com.kotlin.tutorial.user.service.IUserService
  3. import org.springframework.beans.factory.annotation.Autowired
  4. import org.springframework.data.redis.core.RedisTemplate
  5. import org.springframework.stereotype.Service
  6.  
  7.  
  8. /**
  9. * Created by tony on 2018/11/13.
  10. */
  11. @Service
  12. class UserServiceImpl : IUserService {
  13.  
  14. @Autowired
  15. lateinit var redisTemplate: RedisTemplate<Any, Any>
  16.  
  17. override fun getUser(username: String): User {
  18.  
  19. var user = redisTemplate.opsForValue().get("user_${username}")
  20.  
  21. if (user == null) {
  22.  
  23. user = User("default","000000")
  24. }
  25.  
  26. return user as User
  27. }
  28.  
  29. override fun createUser(username: String, password: String) {
  30.  
  31. redisTemplate.opsForValue().set("user_${username}", User(username, password))
  32. }
  33.  
  34. }

1.5 创建 Controller

创建一个 UserController,包含 createUser、getUser 两个接口。

  1. import com.kotlin.tutorial.user.User
  2. import com.kotlin.tutorial.user.service.IUserService
  3. import com.kotlin.tutorial.web.dto.HttpResponse
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired
  6. import org.springframework.web.bind.annotation.GetMapping
  7. import org.springframework.web.bind.annotation.RequestMapping
  8. import org.springframework.web.bind.annotation.RequestParam
  9. import org.springframework.web.bind.annotation.RestController
  10.  
  11.  
  12. /**
  13. * Created by tony on 2018/11/13.
  14. */
  15. @RestController
  16. @RequestMapping("/user")
  17. class UserController {
  18.  
  19. @Autowired
  20. lateinit var userService: IUserService
  21.  
  22. @GetMapping("/getUser")
  23. fun getUser(@RequestParam("name") userName: String): HttpResponse<User> {
  24.  
  25. return HttpResponse(userService.getUser(userName))
  26. }
  27.  
  28. @GetMapping("/createUser")
  29. fun createUser(@RequestParam("name") userName: String,@RequestParam("password") password: String): HttpResponse<String> {
  30.  
  31. userService.createUser(userName,password)
  32.  
  33. return HttpResponse("create ${userName} success")
  34. }
  35. }

创建完 Controller 之后,可以进行测试了。

创建用户tony:

查询用户tony:

创建用户monica:

查询用户monica:

示例二:结合 RxJava 模拟顺序、并发地执行任务

2.1 创建 MockTask

首先定义一个任务接口,所有的任务都需要实现该接口:

  1. /**
  2. * Created by tony on 2018/11/13.
  3. */
  4. interface ITask {
  5.  
  6. fun execute()
  7. }

再创建一个模拟的任务,其中delayInSeconds用来模拟任务所花费的时间,单位是秒。

  1. import java.util.concurrent.TimeUnit
  2. import com.kotlin.tutorial.task.ITask
  3.  
  4. /**
  5. * Created by tony on 2018/11/13.
  6. */
  7. class MockTask(private val delayInSeconds: Int) : ITask {
  8.  
  9. /**
  10. * Stores information if task was started.
  11. */
  12. var started: Boolean = false
  13.  
  14. /**
  15. * Stores information if task was successfully finished.
  16. */
  17. var finishedSuccessfully: Boolean = false
  18.  
  19. /**
  20. * Stores information if the task was interrupted.
  21. * It can happen if the thread that is running this task was killed.
  22. */
  23. var interrupted: Boolean = false
  24.  
  25. /**
  26. * Stores the thread identifier in which the task was executed.
  27. */
  28. var threadId: Long = 0
  29.  
  30. override fun execute() {
  31. try {
  32. this.threadId = Thread.currentThread().id
  33. this.started = true
  34. TimeUnit.SECONDS.sleep(delayInSeconds.toLong())
  35. this.finishedSuccessfully = true
  36. } catch (e: InterruptedException) {
  37. this.interrupted = true
  38. }
  39.  
  40. }
  41. }

2.2 创建 ConcurrentTasksExecutor

顺序执行的话比较简单,一个任务接着一个任务地完成即可,是单线程的操作。

对于并发而言,在这里借助 RxJava 的 merge 操作符来将多个任务进行合并。还用到了 RxJava 的任务调度器 Scheduler,createScheduler()是按照所需的线程数来创建Scheduler的。

  1. import com.kotlin.tutorial.task.ITask
  2. import io.reactivex.Completable
  3. import io.reactivex.schedulers.Schedulers
  4. import org.slf4j.LoggerFactory
  5. import org.springframework.util.CollectionUtils
  6. import java.util.*
  7. import java.util.concurrent.Executors
  8. import java.util.stream.Collectors
  9.  
  10.  
  11. /**
  12. * Created by tony on 2018/11/13.
  13. */
  14. class ConcurrentTasksExecutor(private val numberOfConcurrentThreads: Int, private val tasks: Collection<ITask>?) : ITask {
  15.  
  16. val log = LoggerFactory.getLogger(this.javaClass)
  17.  
  18. constructor(numberOfConcurrentThreads: Int, vararg tasks: ITask) : this(numberOfConcurrentThreads, if (tasks == null) null else Arrays.asList<ITask>(*tasks)) {}
  19.  
  20. init {
  21.  
  22. if (numberOfConcurrentThreads < 0) {
  23. throw RuntimeException("Amount of threads must be higher than zero.")
  24. }
  25. }
  26.  
  27. /**
  28. * Converts collection of tasks (except null tasks) to collection of completable actions.
  29. * Each action will be executed in thread according to the scheduler created with [.createScheduler] method.
  30. *
  31. * @return list of completable actions
  32. */
  33. private val asConcurrentTasks: List<Completable>
  34. get() {
  35.  
  36. if (tasks!=null) {
  37.  
  38. val scheduler = createScheduler()
  39.  
  40. return tasks.stream()
  41. .filter { task -> task != null }
  42. .map { task ->
  43. Completable
  44. .fromAction {
  45. task.execute()
  46. }
  47. .subscribeOn(scheduler)
  48. }
  49. .collect(Collectors.toList())
  50. } else {
  51.  
  52. return ArrayList<Completable>()
  53. }
  54. }
  55.  
  56. /**
  57. * Checks whether tasks collection is empty.
  58. *
  59. * @return true if tasks collection is null or empty, false otherwise
  60. */
  61. private val isTasksCollectionEmpty: Boolean
  62. get() = CollectionUtils.isEmpty(tasks)
  63.  
  64.  
  65. /**
  66. * Executes all tasks concurrent way only if collection of tasks is not empty.
  67. * Method completes when all of the tasks complete (or one of them fails).
  68. * If one of the tasks failed the the exception will be rethrown so that it can be handled by mechanism that calls this method.
  69. */
  70. override fun execute() {
  71.  
  72. if (isTasksCollectionEmpty) {
  73. log.warn("There are no tasks to be executed.")
  74. return
  75. }
  76.  
  77. log.debug("Executing #{} tasks concurrent way.", tasks?.size)
  78. Completable.merge(asConcurrentTasks).blockingAwait()
  79. }
  80.  
  81. /**
  82. * Creates a scheduler that will be used for executing tasks concurrent way.
  83. * Scheduler will use number of threads defined in [.numberOfConcurrentThreads]
  84. *
  85. * @return scheduler
  86. */
  87. private fun createScheduler() = Schedulers.from(Executors.newFixedThreadPool(numberOfConcurrentThreads))
  88. }

2.3 创建 Controller

创建一个 TasksController,包含 sequential、concurrent 两个接口,会分别把sequential 和 concurrent 执行任务的时间展示出来。

  1. import com.kotlin.tutorial.task.impl.ConcurrentTasksExecutor
  2. import com.kotlin.tutorial.task.impl.MockTask
  3. import com.kotlin.tutorial.web.dto.TaskResponse
  4. import com.kotlin.tutorial.web.dto.ErrorResponse
  5. import com.kotlin.tutorial.web.dto.HttpResponse
  6. import org.springframework.http.HttpStatus
  7. import org.springframework.util.StopWatch
  8. import org.springframework.web.bind.annotation.*
  9. import java.util.stream.Collectors
  10. import java.util.stream.IntStream
  11.  
  12. /**
  13. * Created by tony on 2018/11/13.
  14. */
  15. @RestController
  16. @RequestMapping("/tasks")
  17. class TasksController {
  18.  
  19. @GetMapping("/sequential")
  20. fun sequential(@RequestParam("task") taskDelaysInSeconds: IntArray): HttpResponse<TaskResponse> {
  21.  
  22. val watch = StopWatch()
  23. watch.start()
  24.  
  25. IntStream.of(*taskDelaysInSeconds)
  26. .mapToObj{
  27. MockTask(it)
  28. }
  29. .forEach{
  30. it.execute()
  31. }
  32.  
  33. watch.stop()
  34. return HttpResponse(TaskResponse(watch.totalTimeSeconds))
  35. }
  36.  
  37. @GetMapping("/concurrent")
  38. fun concurrent(@RequestParam("task") taskDelaysInSeconds: IntArray, @RequestParam("threads",required = false,defaultValue = "1") numberOfConcurrentThreads: Int): HttpResponse<TaskResponse> {
  39.  
  40. val watch = StopWatch()
  41. watch.start()
  42.  
  43. val delayedTasks = IntStream.of(*taskDelaysInSeconds)
  44. .mapToObj{
  45. MockTask(it)
  46. }
  47. .collect(Collectors.toList())
  48.  
  49. ConcurrentTasksExecutor(numberOfConcurrentThreads, delayedTasks).execute()
  50.  
  51. watch.stop()
  52. return HttpResponse(TaskResponse(watch.totalTimeSeconds))
  53. }
  54.  
  55. @ExceptionHandler(IllegalArgumentException::class)
  56. @ResponseStatus(HttpStatus.BAD_REQUEST)
  57. fun handleException(e: IllegalArgumentException) = ErrorResponse(e.message)
  58. }

顺序地执行多个任务: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

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对w3xue的支持。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号