使用Kotlin和Spring Boot构建的应用程序,通过访问MySQL来实现Hello World

在本文中,我们将使用Kotlin、Spring Boot和MySQL来保存和输出Hello World。

准备MySQL镜像,并使用docker-compose进行启动。

version: '3'
services:
    mysql:
        image: mysql:5.7
        container_name: mysql_playground
        environment:
            MYSQL_ROOT_PASSWORD: mysql
            MYSQL_DATABASE: playground
            MYSQL_USER: docker
            MYSQL_PASSWORD: docker
        volumes:
            ./mysql/init:/docker-entrypoint-initdb.d
        ports:
            3306:3306

将SQL文件存储在/docker-entrypoint-initidb.d中,容器启动时将自动执行。

在这里存储着创建数据库和表的DDL SQL语句。

CREATE TABLE hello_worlds
(
    `id`   int(11)      NOT NULL AUTO_INCREMENT,
        `hello_world` varchar(100) NOT NULL DEFAULT 'Hello, World!',
        PRIMARY KEY (id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

由于docker-compose的配置已完成,将进行启动确认。

$ docker-compose up
Creating network "simple-mysql_default" with the default driver
Creating mysql_helloworld ... done
Attaching to mysql_helloworld 
mysql_helloworld | Initializing database
(...)
mysql_helloworld | 2019-12-28T02:39:53.408712Z 0 [Note] mysqld: ready for connections.
mysql_helloworld | Version: '5.7.27'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)

成功启动了,接下来我们将使用本地的mysql命令连接到已启动的MySQL。

$ mysql -h 0.0.0.0 -u helloworld_user -p
mysql>  SHOW VARIABLES LIKE "%version%";
+-------------------------+------------------------------+
| Variable_name           | Value                        |
+-------------------------+------------------------------+
| innodb_version          | 5.7.27                       |
| protocol_version        | 10                           |
| slave_type_conversions  |                              |
| tls_version             | TLSv1,TLSv1.1                |
| version                 | 5.7.27                       |
| version_comment         | MySQL Community Server (GPL) |
| version_compile_machine | x86_64                       |
| version_compile_os      | Linux                        |
+-------------------------+------------------------------+
8 rows in set (0.01 sec)

准备一个Spring Boot应用程序

以下是前篇文章中创建的基于Kotlin和Spring Boot应用程序的返回Hello World的端点的实现作为基础。

首先,将Spring JPA和MySQL Driver添加到依赖项中(由于是kts文件,请小心)。

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    runtimeOnly ("mysql:mysql-connector-java")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    testImplementation("org.springframework.boot:spring-boot-starter-test") {
        exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
    }
}

一旦完成Dependencies的设置后,接下来需要写下连接MySQL所需要的连接信息。

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://0.0.0.0:3306/helloworld
spring.datasource.username=helloworld_user
spring.datasource.password=helloworld

通过这个应用程序,连接设置已经完成。接下来我们将编写代码来实际使用MySQL。

    @RestController
    class HelloWorldController(private val service: HelloWorldService) {
        @GetMapping("/hello-worlds/{id}")
        fun getHelloWorld(@PathVariable("id") id: Int) = service.getHelloWorld(id)

        @GetMapping("/hello-worlds")
        fun getHelloWorldList() = service.getHelloWorldList()
        @PostMapping("/hello-worlds")
        fun saveHelloWorld(@RequestParam("message") message: String) =
            service.insertHelloWorld(message)
    }
    @Service
    class HelloWorldService(
        private val repository: HelloWorldRepository
    ) {
        fun getHelloWorld(id: Int) = repository.findById(id)
        fun getHelloWorldList() = repository.findAll()
        fun insertHelloWorld(message: String) = HelloWorld(message).let { repository.save(it) }
    }
    interface HelloWorldRepository : CrudRepository<HelloWorld, Int>
    @Entity
    data class HelloWorld(
        var message: String = "Hello, World!",
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        var id: Int = 0
    )

以上是应用程序代码的编写完成。

启动应用程序,使用curl进行POST和GET请求,保存和获取Hello World,就像上一次一样。

$ gradle bootRun
(...)
2019-12-28 12:15:00.727  INFO 52141 --- [           main] c.e.helloworld.HelloworldApplicationKt   : Started HelloworldApplicationKt in 4.021 seconds (JVM running for 4.415)

$ curl -X POST --data 'message=Hello, World!' localhost:8080/hello-worlds
{"message":"Hello, World!","id":1}

$ curl -X POST --data 'message=Hello, World!' localhost:8080/hello-worlds
{"message":"Hello, World!","id":2}

$ curl localhost:8080/hello-worlds/1
{"message":"Hello, World","id":1}

$ curl localhost:8080/hello-worlds
[{"message":"Hello, World!","id":1},{"message":"Hello, World!","id":2}]

你好,世界!

广告
将在 10 秒后关闭
bannerAds