yoshixmk
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Ktor勉強会 #002 ## 前回までの内容 - HackMD - https://hackmd.io/X2DfW4rlTiaU-4l-OiSs9A?view - Gist(HackMDの内容と同じ) - https://gist.github.com/yoshixmk/6dd82c8c3d1975e9229a0aa93eccde7c - repository - https://github.com/yoshixmk/ktor-sample ## 参加者 - うえき - やました - あっきー ## 開催日 2020/05/04(月) 13:15~ ## 宿題 - 下記をお願いした。 - 各自、興味のあるコンテンツがあれば、調べて発表する - 関連して話したいことがあれば、考えておく - (重要)強制ではないので、なければないでOK ## TODO ### ツールの切り替え Zoom -> Google Meet + なんとか開始できた ### Gradle環境のバージョン見直し - 前回の勉強会で、手動installしてしまったのだがこれは不要であったため、各自見直す。 - 本来gradlewはgradleをラップしており、 `./gradlew run` など実行した際に、必要であれば特定のバージョンをダウンロードしてくれる機能を提供する。これによって環境差異が出ない。 - `gradle-wrapper.properties`のバージョンを書き換える ```yml:gradle-wrapper.properties distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip ``` ## Agenda ### アプリケーションビルド(パッケージング) - shadow - https://github.com/johnrengelman/shadow - ビルド成果物をJarファイルとして固めてくれます - 最新のGradle6.3対応はまだ([リリース](https://github.com/johnrengelman/shadow/releases)見ると6.0まで)に見えるので、5.xで進めます - `gradle.properties`の変更 ```gradle:gradle.properties shadow_version=5.2.0 ``` - `build.gradle`の変更 ```gradle:build.gradle buildscript { ... dependencies { ... classpath "com.github.jengelman.gradle.plugins:shadow:$shadow_version" } } ・・・ apply plugin: "com.github.johnrengelman.shadow" ・・・ shadowJar { baseName = 'ktor-sample' classifier = '' version = "$version" } ``` ※ ↑baseName、classifier、versionの指定が@Deprecatedなので、みんなで調べてみる。 - アプリケーションビルド(パッケージング)手順 1. `./gradlew build` 2. (Optional) InteliJ IDEAに設定する時のイメージはこのように設定できる ![](https://i.imgur.com/BIVklxr.png) - うまく生成できていると、`build/libs`にjarファイルができているはずです。 - (余談)フォーマットは、`<baseName>-<version>-<classifier>.jar`で、設定した。ただ、Gradle6系や、値に`default value`があったりするのでおかしければ[ドキュメント](https://docs.gradle.org/6.3/dsl/org.gradle.api.tasks.bundling.AbstractArchiveTask.html#org.gradle.api.tasks.bundling.AbstractArchiveTask:version)読むことをお勧めする。 - ここの[参考](https://jp.ktor.work/quickstart/quickstart/docker.html#gradle%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%9F%E3%82%A2%E3%83%97%E3%83%AA%E3%82%B1%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AE%E3%83%91%E3%83%83%E3%82%B1%E3%83%BC%E3%82%B8%E3%83%B3%E3%82%B0)をベースに進めまてます ### Docker、及び、docker-composeのインストール 情報はたくさんあるので、ここでは割愛します。 docker-composeはおまけで紹介する感じ。 ### Dockerビルド Dockerについてのイメージを掴むため、まずはDockerfileを作ってみます。 下記で、Ktorに適した環境を、運用目線で選定していきます。 - [AdoptOpenJDK](https://adoptopenjdk.net/)が ~~個人的には好き~~ おすすめなので、`adoptopenjdk:11-jre-hotspot`を使用する - 詳しい比較理由は[こちら](https://qiita.com/u-tanick/items/bb166929a58a4c20bb88#-%E3%83%9E%E3%83%AB%E3%83%81%E3%83%97%E3%83%A9%E3%83%83%E3%83%88%E3%83%95%E3%82%A9%E3%83%BC%E3%83%A0%E5%90%91%E3%81%91) - [Dockerhub image](https://hub.docker.com/_/adoptopenjdk) - jdk8でKotlinはビルドするので、後方互換性のある11であれば、動くはずである。そのため、今回は新しいLTSである、11を使用した。 - あとのことも考えて、Volumeマウントの上で実行した場合に、環境変数で外からJarファイルを指定できるようにしておく。 ```Dockerfile: Dockerfile FROM adoptopenjdk:11-jre-hotspot-bionic ENV APPLICATION_USER ktor RUN mkdir /app RUN groupadd --gid 10001 $APPLICATION_USER && \ useradd --gid 10001 --uid 10001 --home-dir /app $APPLICATION_USER RUN chown -R $APPLICATION_USER /app USER $APPLICATION_USER ENV JAR_FILENAME ktor-sample-0.0.1-SNAPSHOT.jar COPY ./build/libs/$JAR_FILENAME /app/$JAR_FILENAME WORKDIR /app CMD ["bash", "-c", "java -jar $JAR_FILENAME"] ``` - ※ CMD内で環境変数を使用するには、シェル経由にする必要がある。 - 設定のベースは[ここを参照](https://jp.ktor.work/quickstart/quickstart/docker.html#docker%E3%82%A4%E3%83%A1%E3%83%BC%E3%82%B8%E3%81%AE%E6%BA%96%E5%82%99)した ### Dockerの起動し、動作確認する - 予め、アプリケーションビルド(パッケージング)して、Jarファイルををしておく。 - `docker build -t ktor-sample .` - この時、Dockerfile内の `JAR_FILENAME` の名称が実際に吐き出されたjarファイルと一致すること。`ktor-sample-0.0.1-SNAPSHOT.jar` - `docker run -p 8080:8080 --rm ktor-sample` - http://localhost:8080 へアクセスして、起動していれば成功。 ### DBとの接続 Dockerをイメージしてもらうため、Dockerfileから作成しましたが、 公式イメージ(ゴールデンイメージと言ったりもする)をはじめ、有志が作成したイメージなどは、[Docker Hub](https://hub.docker.com/)にすでにあることが多いです。 例えば、DB(Postgres)を使用し、5432ポートで起動する場合、下記のコマンド1つで動き始めます。 `docker run --rm --name ktor-sample-db -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:12.2` 参考は[公式ドキュメント](https://hub.docker.com/_/postgres) ### docker-compose 細かく話すとあれなので、さらっと。 ```Docker:docker-compose.yml version: "3" services: app: image: ktor-sample:latest build: context: . dockerfile: ./Dockerfile ports: - "8080:8080" depends_on: - db db: image: postgres:12.2 environment: POSTGRES_USER: "postgres" POSTGRES_PASSWORD: "postgres" ports: - "5432:5432" volumes: - db-data:/var/lib/postgresql/data volumes: db-data: driver: local ``` - `docker-compose up -d` - `docker-compose ps` - `docker volume ls` - 確認(app) - http://localhost:8080 - 確認(db) - `docker-compose exec db bash` - `psql -U postgres -h localhost` - postgres=# `\l` - InteliJ IDEAで確認することもできます![](https://i.imgur.com/3g0Z7Dp.png) - `docker-compose down ` ### docker-composeでDBだけ起動 前述のコマンドは長いので、docker-composeの方が、楽なので紹介。 さらに、volume設定してるので、データは永続化されます。(普通のdockerだとvolumeコマンド必要) `docker-compose up -d db` ### アプリケーションから、DBを使用する まずは、SQL Frameworkを決めます。 1. トレンド比較 https://trends.google.co.jp/trends/explore?geo=JP&q=Doma,Exposed,jOOQ 1. Kotlinとの組み合わせということで`Exposed` 次に、[公式Wiki](https://github.com/JetBrains/Exposed/wiki/Getting-Started#gradle)を参考。 - gradle.propertiesに追記。 ```gradle:gradle.properties ・・・ exposed_version=0.23.1 ``` - build.gradleに追記。 ```gradle:build.gradle dependencies { ・・・ compile "org.jetbrains.exposed:exposed-core:$exposed_version" compile "org.jetbrains.exposed:exposed-dao:$exposed_version" compile "org.jetbrains.exposed:exposed-jdbc:$exposed_version" } ``` #### DBのセットアップ&アプリケーションのDB設定 DBの設定周りは、社内エンジニアが書いたブログと同じことやります。 この辺は運用で必ず出てくる話なので、勉強になります - [Flywayでマイグレーション](https://rinoguchi.hatenablog.com/entry/2020/04/24/100000#Flyway%E3%81%A7%E3%83%9E%E3%82%A4%E3%82%B0%E3%83%AC%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3) - src/main/配下ではないため、 - sql dir場所`resources/db/migration/V1__Initial.sql` - target path指定`locations = ['filesystem:resources/db/migration']` - version 6.4.1 - テーブル構造はちょいと変えました。 - memo -> memos - body -> subject, add NOT NULL ```sql:V1__Initial.sql DROP TABLE IF EXISTS memos; CREATE TABLE memos ( memo_id serial PRIMARY KEY, subject text NOT NULL ); INSERT INTO memos (subject) VALUES ('sample1') , ('sample2') , ('sample3') ; ``` ```properties: gradle.properties flywaydb_version=6.4.1 postgresql_version=42.2.12 ``` ```gradle:build.gradle buildscript { repositories { ・・・ maven { url "https://plugins.gradle.org/m2/" } } dependencies { ・・・ classpath "gradle.plugin.org.flywaydb:gradle-plugin-publishing:$flywaydb_version" } } apply plugin: "org.flywaydb.flyway" dependencies { implementation "org.postgresql:postgresql:$postgresql_version" } ・・・ flyway { url = "jdbc:postgresql://localhost:5432/postgres" user = "postgres" password = "postgres" baselineVersion = "1" locations = ['filesystem:resources/db/migration'] } ``` うまくいけば、public.memos(複数形の名称にしてます)ができてるはず ![](https://i.imgur.com/VqnJwym.png) コマンドだと ``` postgres=# \d memos; Table "public.memos" Column | Type | Collation | Nullable | Default ---------+---------+-----------+----------+---------------------------------------- memo_id | integer | | not null | nextval('memos_memo_id_seq'::regclass) subject | text | | not null | ``` - [DBにアクセスする](https://rinoguchi.hatenablog.com/entry/2020/04/24/100000#DB%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%E3%81%99%E3%82%8B) Application.kt に追加 (moduleの内部)。汚いので、あとでいい方法を探します ```kotlin= if (environment.config.propertyOrNull("ktor.deployment.environment") == null) { val config = environment.config Database.connect( url = config.property("database.url").getString(), user = config.property("database.user").getString(), password = config.property("database.password").getString(), driver = "org.postgresql.Driver" ) } ``` テーブルを表すオブジェクトクラスを作成 `Memo.kt` としました。 ```kotlin= object Memos : IntIdTable("memos", "memo_id") { val subject = text("subject") } class Memo(memoId: EntityID<Int>) : IntEntity(memoId) { companion object : IntEntityClass<Memo>(Memos) val subject by Memos.subject } ``` #### ここまでの修正内容はこちら https://github.com/yoshixmk/ktor-sample/pull/1/files ### POSTリクエストでデータを送って、memosテーブルにデータを書き込んでみる - POST: /memos - body ↓ ```json:request-body { "subject": "これはメモです" } ``` - Response 201 (Created) - 挿入したメモのID!!! ちゅうい + request bodyを受けとる ```kotlin= val parameter = call.receive<HogeHoge>() ``` + exposedで挿入する ```kotlin= val id = transaction { Memos.insertAndGetId { it[subject] = parameter.subject } } ``` + 201 (Created) を返したい ```kotlin= call.respond( HttpStatusCode.Created, mapOf( "key1" to "value1", "key2" to "value2" ) ) ``` - 201を返す(植木ver) - `MemoPostInput.kt`は、別クラスに切り分けて配置すること。(クラスを別にしない場合は、`JsonMappingException: Cannot deserialize Class`となります。) ```kotlin= post<MemoPostInput>("/memos") { input -> call.respond( HttpStatusCode.Created, mapOf( "memo_id" to transaction { Memo.new { this.subject = input.subject } }.id.value ) ) } ``` ```kotlin= data class MemoPostInput(val subject: String) ``` ### (やりたい人は、応用問題) docker-composeで、アプリケーションからDBへ接続できるように設定を変えてみる - Docker内部のネットワークは、db:8080で接続できます ### きょうの成果 * うえき * あっきー * やました https://github.com/jamashita/demo-comprendre/releases/tag/20200504 ### Memo ### 次回について 2020/05/09(土) 13:00ごろ #### 宿題 - 下記をお願いした。 - 各自、興味のあるコンテンツがあれば、調べて発表する - 関連して話したいことがあれば、考えておく - (重要)強制ではないので、なければないでOK

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully