使用 Kotlin + Spring Boot 进行后端开发

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: 使用 Kotlin + Spring Boot 进行后端开发

Kotlin



Kotlin 是一个基于 JVM 的编程语言,它的简洁、便利早已不言而喻。Kotlin 能够胜任 Java 做的所有事。目前,我们公司 C 端 的 Android 产品全部采用 Kotlin 编写。公司的后端项目也可能会使用 Kotlin,所以我给他们做一些 demo 进行演示。


示例一:结合 Redis 进行数据存储和查询



1.1 配置 gradle


在build.gradle中添加插件和依赖的库。

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:

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 的配置

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等都可以,看个人喜好。

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

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 类型。

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

创建操作 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)
}


创建 Service 的实现类:

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 两个接口。

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:


image.png

创建用户tony.png


查询用户tony:

image.png

查询用户tony.jpeg


创建用户monica:

image.png

创建用户monica.jpeg


查询用户monica:

image.png

查询用户monica.jpeg


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



2.1 创建 MockTask


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

/**
 * Created by tony on 2018/11/13.
 */
interface ITask {
    fun execute()
}


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

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的。

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 执行任务的时间展示出来。

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


image.png

顺序执行多个任务.jpeg


每个任务所花费的时间分别是1秒、2秒、3秒和4秒。最后,一共花费了10.009秒。


两个线程并发地执行多个任务:http://localhost:8080/tasks/concurrent?task=1&task=2&task=3&task=4&threads=2

image.png

两个线程并发执行多任务.jpeg


三个线程并发地执行多个任务:http://localhost:8080/tasks/concurrent?task=1&task=2&task=3&task=4&threads=3

image.png

三个线程并发执行多任务.jpeg


总结



本文使用了 Kotlin 的特性跟 Spring Boot 整合进行后端开发。Kotlin 的很多语法糖使得开发变得更加便利,当然 Kotlin 也是 Java 的必要补充。

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
1天前
|
人工智能 Java API
阿里云工程师跟通义灵码结伴编程, 用Spring AI Alibaba来开发 AI 答疑助手
本次分享的主题是阿里云工程师跟通义灵码结伴编程, 用Spring AI Alibaba来开发 AI 答疑助手,由阿里云两位工程师分享。
阿里云工程师跟通义灵码结伴编程, 用Spring AI Alibaba来开发 AI 答疑助手
|
24天前
|
人工智能 前端开发 Java
Spring AI Alibaba + 通义千问,开发AI应用如此简单!!!
本文介绍了如何使用Spring AI Alibaba开发一个简单的AI对话应用。通过引入`spring-ai-alibaba-starter`依赖和配置API密钥,结合Spring Boot项目,只需几行代码即可实现与AI模型的交互。具体步骤包括创建Spring Boot项目、编写Controller处理对话请求以及前端页面展示对话内容。此外,文章还介绍了如何通过添加对话记忆功能,使AI能够理解上下文并进行连贯对话。最后,总结了Spring AI为Java开发者带来的便利,简化了AI应用的开发流程。
306 0
|
18天前
|
开发框架 小程序 前端开发
圈子社交app前端+后端源码,uniapp社交兴趣圈子开发,框架php圈子小程序安装搭建
本文介绍了圈子社交APP的源码获取、分析与定制,PHP实现的圈子框架设计及代码编写,以及圈子小程序的安装搭建。涵盖环境配置、数据库设计、前后端开发与接口对接等内容,确保平台的安全性、性能和功能完整性。通过详细指导,帮助开发者快速搭建稳定可靠的圈子社交平台。
140 18
|
10天前
|
监控 JavaScript 数据可视化
建筑施工一体化信息管理平台源码,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
智慧工地云平台是专为建筑施工领域打造的一体化信息管理平台,利用大数据、云计算、物联网等技术,实现施工区域各系统数据汇总与可视化管理。平台涵盖人员、设备、物料、环境等关键因素的实时监控与数据分析,提供远程指挥、决策支持等功能,提升工作效率,促进产业信息化发展。系统由PC端、APP移动端及项目、监管、数据屏三大平台组成,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
|
1月前
|
XML JSON Java
Spring Boot 开发中常见的错误
本文总结了 Java 开发中常见的几个问题及其改进方法,包括:1. 过度使用 `@Component` 注解;2. `@ResponseBody` 注解的错误用法;3. `@Autowired` 的不当使用;4. `application.properties` 管理不善;5. 异常处理不当。每部分详细解释了错误情况和建议的改进方案,并提供了相应的代码示例。
55 11
|
30天前
|
机器学习/深度学习 前端开发 算法
婚恋交友系统平台 相亲交友平台系统 婚恋交友系统APP 婚恋系统源码 婚恋交友平台开发流程 婚恋交友系统架构设计 婚恋交友系统前端/后端开发 婚恋交友系统匹配推荐算法优化
婚恋交友系统平台通过线上互动帮助单身男女找到合适伴侣,提供用户注册、个人资料填写、匹配推荐、实时聊天、社区互动等功能。开发流程包括需求分析、技术选型、系统架构设计、功能实现、测试优化和上线运维。匹配推荐算法优化是核心,通过用户行为数据分析和机器学习提高匹配准确性。
92 3
|
1月前
|
IDE Java 测试技术
互联网应用主流框架整合之Spring Boot开发
通过本文的介绍,我们详细探讨了Spring Boot开发的核心概念和实践方法,包括项目结构、数据访问层、服务层、控制层、配置管理、单元测试以及部署与运行。Spring Boot通过简化配置和强大的生态系统,使得互联网应用的开发更加高效和可靠。希望本文能够帮助开发者快速掌握Spring Boot,并在实际项目中灵活应用。
51 5
|
29天前
|
前端开发 Java 开发者
这款免费 IDEA 插件让你开发 Spring 程序更简单
Feign-Helper 是一款支持 Spring 框架的 IDEA 免费插件,提供 URL 快速搜索、Spring Web Controller 路径一键复制及 Feign 与 Controller 接口互相导航等功能,极大提升了开发效率。
|
3月前
|
JSON 调度 数据库
Android面试之5个Kotlin深度面试题:协程、密封类和高阶函数
本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一起每天进步一点点。文章详细解析了Kotlin中的协程、扩展函数、高阶函数、密封类及`inline`和`reified`关键字在Android开发中的应用,帮助读者更好地理解和使用这些特性。
49 1
|
4月前
|
Android开发 开发者 Kotlin
告别AsyncTask:一招教你用Kotlin协程重构Android应用,流畅度飙升的秘密武器
【9月更文挑战第13天】随着Android应用复杂度的增加,有效管理异步任务成为关键。Kotlin协程提供了一种优雅的并发操作处理方式,使异步编程更简单直观。本文通过具体示例介绍如何使用Kotlin协程优化Android应用性能,包括网络数据加载和UI更新。首先需在`build.gradle`中添加coroutines依赖。接着,通过定义挂起函数执行网络请求,并在`ViewModel`中使用`viewModelScope`启动协程,结合`Dispatchers.Main`更新UI,避免内存泄漏。使用协程不仅简化代码,还提升了程序健壮性。
145 1

热门文章

最新文章