LoginSignup
18
10

More than 1 year has passed since last update.

.NET 6 と Daprを使った分散サービス開発 その1 環境構築

Last updated at Posted at 2022-03-01

Daprについて

Dapr https://dapr.io/ は、マイクロサービスなどで、共通にしておくと便利になりそうな関心事をサイドカーライブラリとして実装したものです。今のところは、以下のようなコンポーネントをアプリケーションから呼び出す事ができます。開発環境もWindows,Mac,Linux問わず、様々な開発言語でマイクロサービスの開発を行うことができます。

image.png

  • Service Invocation (サービス間起動)
  • State Management (ステート管理)
  • Publish & Subscribe (パブリッシュ & サブスクライブ)
  • Bindings (バインド)
  • Observability (観測可能性)
  • Secrets management (シークレット・鍵管理)
  • Actors (アクターサービスモデル)

また、以下のように各コンポーネントは設定によって、マイクロサービスの稼働環境が自社データセンターの Kubernetes でも、AzureやAWS、GCPなどのKubernetes などの環境でも、差し替えて稼働させる事ができます。例えば、自社データセンターでは、ステートストアを Redis で運用していたとして、AzureではCosmos DBへ、AWSではDynamo DBへ、GCPではFirebaseでなど差し替えを行い、コードは修正が不要になります。

image.png

マイクロサービスの開発では、各サービスを個別にスケールアウトしたりと有用性もある反面、開発する現場では様々な課題があると思います。

  • サービス連携してRESTをコールした際、どこで問題が起こったのか分かりづらい、デバッグなどに苦労する
  • 各マイクロサービスの実装で共通化しておきたいデータストアがバラバラで一貫性が無い
  • モニタリング、分散トレーシングの仕組みが共通化されておらず、すべて個別に作られてしまっていた
  • 自分のローカル環境で再現する際に、サービスやコンテナイメージの依存性解決に腐心する

などなど・・・あると思います。
Daprは、このようなケースを解決しようと開発された開発フレームワークです。

Dapr環境準備

ローカル環境で構築できる事は、後にデバッグなどで再現する上でも大事です。まずは、ローカル環境で構築してみましょう。

Dapr CLIのインストール

ここから https://docs.dapr.io/getting-started/ からインストールのStep by Stepがあります。
基本的にはWindowsであれ、Macであれ、Linuxであれ、バイナリダウンロードしてパス切っているって感じのスクリプトになっています。

インストールが終わると、Windowsの場合であれば、C:ドライブ直下にDaprというフォルダができ、そこにパスが切られて、Dapr.exeが配置されます。

インストール

以下のスクリプトは管理者権限で実行しましょう。

powershell -Command "iwr -useb https://raw.githubusercontent.com/dapr/cli/master/install/install.ps1 | iex"

インストールに失敗する場合

スクリプトが実行できない場合、もしかしたら、Powershellのスクリプト実行がNGになっているかもしません、その場合は実行ポリシーを少し緩めてください。

Set-ExecutionPolicy RemoteSigned

Windows Terminalやコマンドプロンプトから dapr を入力して以下のように表示されればCLIはインストールできています。

$ dapr
         __
    ____/ /___ _____  _____
   / __  / __ '/ __ \/ ___/
  / /_/ / /_/ / /_/ / /
  \__,_/\__,_/ .___/_/
              /_/

===============================
Distributed Application Runtime

Usage:
  dapr [command]

Available Commands:
  build-info     Print build info of Dapr CLI and runtime
  completion     Generates shell completion scripts
  components     List all Dapr components. Supported platforms: Kubernetes
  configurations List all Dapr configurations. Supported platforms: Kubernetes
  dashboard      Start Dapr dashboard. Supported platforms: Kubernetes and self-hosted
  help           Help about any command
  init           Install Dapr on supported hosting platforms. Supported platforms: Kubernetes and self-hosted
  invoke         Invoke a method on a given Dapr application. Supported platforms: Self-hosted
  list           List all Dapr instances. Supported platforms: Kubernetes and self-hosted
  logs           Get Dapr sidecar logs for an application. Supported platforms: Kubernetes
  mtls           Check if mTLS is enabled. Supported platforms: Kubernetes
  publish        Publish a pub-sub event. Supported platforms: Self-hosted
  run            Run Dapr and (optionally) your application side by side. Supported platforms: Self-hosted
  status         Show the health status of Dapr services. Supported platforms: Kubernetes
  stop           Stop Dapr instances and their associated apps. Supported platforms: Self-hosted
  uninstall      Uninstall Dapr runtime. Supported platforms: Kubernetes and self-hosted
  upgrade        Upgrades or downgrades a Dapr control plane installation in a cluster. Supported platforms: Kubernetes

Flags:
  -h, --help          help for dapr
      --log-as-json   Log output in JSON format
  -v, --version       version for dapr

Use "dapr [command] --help" for more information about a command.

Docker Desktopのインストール

Daprでは、dockerを使わないモードもありますが、機能制限もあるのでdockerコマンドが使える環境を作ります。既に入っている場合は、ここはスキップして大丈夫です。

インストールしたら、以下のコマンドを確認しておいてください。

$ docker

Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default
                           "C:\\Users\\kahiro\\.docker")
  -c, --context string     Name of the context to use to connect to the
                           daemon (overrides DOCKER_HOST env var and
                           default context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level
                           ("debug"|"info"|"warn"|"error"|"fatal")
                           (default "info")

.NET 6のインストール

.NET 6 (SDK)をインストール Linux、macOS、Windowsそれぞれあるので、環境に合わせて導入してください。

$ dotnet

Usage: dotnet [options]
Usage: dotnet [path-to-application]

Options:
  -h|--help         Display help.
  --info            Display .NET information.
  --list-sdks       Display the installed SDKs.
  --list-runtimes   Display the installed runtimes.

path-to-application:
  The path to an application .dll file to execute.

Tyeのインストール

マイクロサービスでは、様々なプロジェクトを個別に起動しなければならず、加えてサービス同士のデバッグを行うために他のサービスを起動して・・・みたいな事は非常に面倒です。そこで、起動管理、イメージビルドツールとしてtyeを使います。tyeはプロジェクトの起動とDaprをサイドカーとして起動してくれたり、サービスに依存するdockerイメージを起動してくれたり、Dockerfileが無くとも、各プロジェクトのdockerイメージを自動作成してくれたり、Kubernetes への自動デプロイメントしてくれるなど便利なツールです。

$ dotnet tool install -g Microsoft.Tye --version "0.11.0-alpha.22111.1"
次のコマンドを使用してツールを呼び出せます。tye
ツール 'microsoft.tye' (バージョン '0.11.0-alpha.22111.1') が正常にインストールされました。

確認

$ tye
tye:
  Developer tools and publishing for microservices.

Usage:
  tye [options] [command]

Options:
  --no-default      Disable default options from environment variables
  -?, -h, --help    Show help and usage information
  --version         Show version information

Commands:
  init <path>        create a yaml manifest
  run <path>         run the application
  build <path>       build containers for the application
  push <path>        build and push application containers to registry
  deploy <path>      deploy the application
  undeploy <path>    delete deployed application

Daprの初期設定 (初回のみ)

次にDaprを初期設定します。前述の通り、ステートストアなど一部のコンポーネントを使う上では、Redisなどをあらかじめインストールして設定を行う必要があります。今回は開発環境構築を自分のローカルに行いますので、手早く終わらせたいと思っています。

Dapr initを実行する事で、開発環境向けにRedisのコンテナイメージなどダウンロードしてセットアップしてくれます。

$ dapr init
Making the jump to hyperspace...
Installing runtime version 1.6.0
Downloading binaries and setting up components...
Downloaded binaries and completed components set up.
daprd binary has been installed to C:\Users\kahiro\.dapr\bin.
dapr_placement container is running.
dapr_redis container is running.
dapr_zipkin container is running.
Use `docker ps` to check running containers.
Success! Dapr is up and running. To get started, go here: https://aka.ms/dapr-getting-started

initされた結果、redisやzipkinがコンテナとして起動しました。

$ docker ps
CONTAINER ID   IMAGE               COMMAND                  CREATED          STATUS                 PORTS                              NAMES
ba8a9bdb62ab   daprio/dapr:1.6.0   "./placement"            43 seconds ago   Up 42 seconds          0.0.0.0:6050->50005/tcp            dapr_placement
808b6358b4e7   openzipkin/zipkin   "start-zipkin"           43 seconds ago   Up 42 seconds          9410/tcp, 0.0.0.0:9411->9411/tcp   dapr_zipkin
bed085e54a77   redis               "docker-entrypoint.s…"   43 seconds ago   Up 42 seconds          0.0.0.0:6379->6379/tcp             dapr_redis

$ docker images
REPOSITORY          TAG       IMAGE ID       CREATED       SIZE
redis               latest    f1b6973564e9   4 weeks ago   113MB
daprio/dapr         1.6.0     16197c2648b6   5 weeks ago   217MB
openzipkin/zipkin   latest    8911130146d1   8 weeks ago   155MB

次は実際にプロジェクトを作り、DebugやStep実行などを行ってみます。

18
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
10