Daprは、開発者が分散システムの複雑さに集中せず、柔軟な無状態・有状態アプリケーションを簡単に構築できるポータブルなイベント駆動型ランタイムです。クラウドまたはエッジ環境で動作し、複数のプログラミング言語とフレームワークをサポートしています。Daprは、現代的なクラウドネイティブアプリケーションの構築を大幅に簡素化します。
クラウドネイティブマイクロサービスの実装ステップ
Dapr CLIのインストール
MacOSおよびDapr 1.8の場合:
sudo curl -fsSL https://raw.githubusercontent.com/dapr/cli/master/install/install.sh | /bin/bash
Linux/Windowsのインストール方法:
ローカル環境でのDapr初期化
初期化には以下が含まれます:
- 状態ストレージとメッセージ代理としてのRedisコンテナインスタンスの起動
- 可観測性を提供するZipkinコンテナインスタンスの起動
- 上記コンポーネント定義を含むデフォルトコンポーネントフォルダの作成
- ローカルアクター(サービス)をサポートするDapr placementサービスコンテナインスタンスの起動
CLIコマンドでの初期化実行
dapr init
Daprバージョンの確認
dapr -v
CLI version: 1.8.0
Runtime version: 1.8.0
コンテナの起動確認
dapr initコマンドは、daprio/dapr、openzipkin/zipkin、redisイメージのコンテナインスタンスを起動します。
コンポーネントディレクトリの初期化確認
dapr init実行時にCLIはデフォルトコンポーネントフォルダを作成し、状態ストレージ、Pub/sub、Zipkinの定義を含むYAMLファイルを配置します。Dapr sidecarはこれらのコンポーネントを読み込みます。
- Windows:
%UserProfile%\.dapr - Linux/MacOS:
~/.dapr
ls $HOME/.dapr
bin components config.yaml
Dapr APIの使用
Dapr sidecarの起動とState APIのテスト
dapr run --app-id myapp --dapr-http-port 3500
状態の保存
curl -X POST -H "Content-Type: application/json" -d '[{ "key": "user", "value": "Alice Johnson"}]' http://localhost:3500/v1.0/state/datastore
状態の取得
curl http://localhost:3500/v1.0/state/datastore/user
Redisでの状態確認
docker exec -it dapr_redis redis-cli
keys *
"myapp||user"
hgetall "myapp||user"
1) "data"
2) "\"Alice Johnson\""
3) "version"
4) "1"
exit
状態の削除
curl -v -X DELETE -H "Content-Type: application/json" http://localhost:3500/v1.0/state/datastore/user
実装ガイドライン
サービス間通信
例: 注文処理サービスの実装
git clone https://github.com/dapr/quickstarts.git
cd service_invocation/typescript/http/order-handler
npm install
dapr run --app-id order-handler --dapr-http-port 3501 -- npm start
コード例:
app.post('/transactions', (req, res) => {
console.log("Transaction received:", req.body);
res.sendStatus(200);
});
注文処理サービスの呼び出し:
cd service_invocation/typescript/http/payment-service
npm install
dapr run --app-id payment-service --dapr-http-port 3500 -- npm start
API呼び出しコード:
const config = {
headers: {
"dapr-app-id": "order-handler"
}
};
await axios.post(`http://localhost:3500/transactions`, transaction, config);
状態管理の実装
コンポーネント構成ファイル:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: data-store
spec:
type: state.redis
version: v1
metadata:
- name: redisHost
value: localhost:6379
データ操作コード:
const client = new DaprClient("localhost", 3500);
client.state.save("data-store", [
{ key: "tx123", value: { amount: 100, user: "Alice" } }
]);
パブサブの実装
コンポーネント構成ファイル:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: event-broker
spec:
type: pubsub.redis
version: v1
metadata:
- name: redisHost
value: localhost:6379
サブスクライバーコード:
server.pubsub.subscribe("event-broker", "transactions", (data) =>
console.log("Received event:", JSON.stringify(data))
);
パブリッシャーコード:
await client.pubsub.publish("event-broker", "transactions", {
transactionId: "tx456",
amount: 200
});
バインディングの実装
Cronバインディング構成:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: scheduler
spec:
type: bindings.cron
version: v1
metadata:
- name: schedule
value: "@every 5s"
データベースバインディング構成:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: db-connector
spec:
type: bindings.postgres
version: v1
metadata:
- name: url
value: "user=postgres password=docker host=localhost port=5432 dbname=transactions"
バッチ処理コード:
async function processBatch() {
const data = await fs.promises.readFile("transactions.json");
const transactions = JSON.parse(data);
for (const tx of transactions) {
await client.binding.send("db-connector", "insert",
JSON.stringify({
table: "transactions",
values: [tx.id, tx.amount, tx.user]
})
);
}
}
シークレット管理の実装
シークレットストア構成:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: secret-store
spec:
type: secretstores.local.file
version: v1
metadata:
- name: secretsFile
value: .secrets.json
シークレット取得コード:
const secret = await client.secret.get("secret-store", "api_key");
console.log("Retrieved secret:", secret.value);