go-kratos/examples

repository·main·Indexed 19 days ago

https://github.com/go-kratos/examples

A collection of practical examples for the Kratos framework. It covers core components such as configuration, logging, registry, and observability, and includes specific implementations like kratos-casbin for AuthN/AuthZ, kratos-chatroom for WebSockets, and kratos-cqrs for Command Query Responsibility Segregation using Kafka and TimeScaleDB.

Tokens
52.2K
Snippets
177
Records
204
Agent score
63%

What's inside go-kratos-examples

  1. Overview of the Logger Service

    main
    The Logger Service is a specialized service designed for querying log data. To optimize performance and prevent write pressure on the primary database, this service is typically mounted on a database read replica (slave). While this architecture may result in some read latency (eventual consistency), this behavior is considered acceptable for log-based data retrieval.
  2. Overview of kratos-chatroom

    main
    The kratos-chatroom example demonstrates a simple WebSocket-based chat room implementation. In this model, a client sends a message via a WebSocket connection, and the server immediately broadcasts that message to all other connected clients upon receipt.
  3. Overview of kratos-realtimemap

    main

    The kratos-realtimemap project is a real-time public transportation map implementation based on Proto.Actor. It demonstrates how to build a microservices-based real-time system using the Kratos framework.

    Key Features and Architecture

    • Data Ingestion: Uses MQTT to collect open experimental data (based on HFP API or GTFS standards).
    • Communication Patterns:
      • Websocket: Used for streaming real-time telemetry/coordinate data to the frontend.
      • RESTful API: Used for relatively static data such as geofences, vehicle attributes, and historical telemetry data.
    • BFF Pattern: Utilizes Kratos as a Backend-for-Frontend (BFF) to communicate with the web client.
    • Simplified Implementation: For demonstration purposes, this version uses in-memory caching instead of Redis and bypasses Kafka, though a production version would typically pipe MQTT data into Kafka for downstream microservice consumption.
  4. Overview of kratos-cqrs

    main

    The kratos-cqrs project is an experimental implementation of the Command Query Responsibility Segregation (CQRS) pattern using the Kratos microservices framework. It demonstrates how to use Kafka for database write operations within a microservices architecture.

    Because Kratos does not natively support message queues, this project utilizes kratos-transport to provide support for Kafka, RabbitMQ, MQTT, Redis, Websocket, and NATS.

    The architecture is split into two primary microservices:

    1. Log Query Service (kratos.logger.service): Provides a gRPC interface for querying logs and uses the Entgo ORM to perform time-series queries against TimeScaleDB.
    2. Log Write Service (kratos.logger.job): A background worker that connects to Kafka and subscribes to specific topics to persist data.
  5. Explore Kratos feature examples

    main

    The go-kratos/go-kratos/examples repository contains a collection of practical implementations demonstrating various Kratos features and patterns. You can use these examples to understand how to implement specific functionalities in your own Kratos-based microservices.

    Key categories of examples include:

    Security & Authentication

    • JWT: Using JSON Web Tokens for authentication (auth/jwt).
    • Casbin: Combining JWT authentication with Casbin-based authorization (casbin).
    • TLS: Implementing TLS certificate usage (tls).

    Communication & Protocols

    • RPC: Basic Remote Procedure Call examples (helloworld).
    • HTTP: Handling HTTP-specific tasks like CORS and file uploads (http).
    • Websocket: Simple Websocket implementations (ws) and a full chatroom example (chatroom).
    • Streaming: Examples involving streaming data (stream).
    • MQTT & Real-time: Complex integration of MQTT, Websocket, and RPC via the Real-time Bus Map example (realtimemap).

    Infrastructure & Middleware

    • Configuration: Using local files and remote configuration centers (config).
    • Registry: Using service registries (registry).
    • Middleware: Implementing custom middleware (middleware).
    • Error Handling: Managing errors within the framework (errors).
    • Logging & Observability: Using logging (log), metrics (metrics), tracing (traces), and OpenTelemetry (otel).
    • Metadata & Headers: Working with HTTP headers (header) and metadata (metadata).

    Data & Patterns

    • CQRS: Implementing Command Query Responsibility Segregation, primarily using Kafka (cqrs).
    • Messaging: Using Message Queues like Kafka for sending/receiving messages (event).
    • Database: Managing database transactions (transaction).
    • Validation: Using Protobuf parameter validators (validate).
    • CRUD: A simple blog system demonstrating basic Create, Read, Update, and Delete operations (blog).

    API Documentation & Utilities

    • Swagger: Using Swagger for API documentation (swagger).
    • I18n: Implementing internationalization and localization (i18n).
    • Selector: Using node selectors (selector).
  6. Explore Kratos examples

    main

    The examples repository contains various implementations demonstrating different Kratos components and patterns. Use these examples to understand how to implement specific features in your own Kratos projects:

    • Core Components:

      • config: Demonstrates Kratos configuration management.
      • errors: Shows how to handle errors, specifically those generated via proto-gen-go-errors.
      • log: Provides examples for logger, helper, filter, and valuer.
      • metadata: Demonstrates usage of metadata.
      • registry: Shows service registration and discovery using Etcd, Consul, and Nacos.
      • validate: Demonstrates middleware-based validation using code generated by proto-gen-validate.
    • Transport & Communication:

      • http: Examples of HTTP transport usage.
      • ws: Implementation of the transport interface using WebSockets.
      • swagger: Implementation of a server with embedded Swagger API documentation.
    • Observability:

      • metrics: Demonstrates metrics collection using Prometheus (prom).
      • traces: Demonstrates middleware/tracing implemented via OpenTelemetry.
    • Application Patterns:

      • blog: A simple CRUD project.
      • helloworld: A basic
  7. Kafka Client Selection for CQRS Job Data

    main

    When implementing Kafka clients within the CQRS job data layer, use the Confluent Go client (confluent-kafka-go/kafka) instead of Sarama.

    Sarama is avoided due to the following known issues:

    • Partition Awareness: Sarama cannot detect new partitions added to a Topic without a client restart.
    • Multi-Topic Subscription: Subscribing to two or more Topics simultaneously can lead to certain partitions failing to consume messages correctly.
    • Offset Reset Risks: When the consumer offset reset strategy is set to Oldest(earliest), Sarama's internal implementation of the OutOfRange mechanism may cause the client to re-consume all messages from the beginning if the client crashes or the server version is upgraded.
  8. Kafka Client Selection in CQRS Example

    main

    In the cqrs/app/logger/service implementation, the project uses the Confluent Go client (confluent-kafka-go/kafka) instead of the Sarama client.

    This decision was made to avoid several known issues with the Sarama Go client:

    1. Partition Awareness: Sarama cannot detect when new partitions are added to a Topic without a client restart.
    2. Multi-Topic Subscription: Subscribing to two or more Topics simultaneously in Sarama can lead to certain partitions failing to consume messages correctly.
    3. Offset Reset Risks: When the consumer offset reset strategy is set to Oldest(earliest), Sarama's custom implementation of the OutOfRange mechanism can cause the client to re-consume all messages from the beginning if the client crashes or the server version is upgraded.

    For more technical depth on these issues, refer to the documentation provided by Alibaba Cloud or general Kafka development guides.

  9. Understand the AuthN and AuthZ implementation in kratos-casbin

    main

    The kratos-casbin example demonstrates how to combine Authentication (AuthN) and Authorization (AuthZ) within a Kratos microservice architecture:

    • AuthN (Authentication): Uses JWT (JSON Web Tokens) to establish user identity. The system verifies who the user is via a login process that issues a token.
    • AuthZ (Authorization): Uses Casbin to establish privileges. Once the identity is known, Casbin determines what actions that identity is allowed to perform.

    In this specific example, roles are used to restrict UI visibility (e.g., admin, moderator, and user), though the implementation demonstrates permission limiting via usernames.

  10. Use protoc-gen-validate (PGV) for Protobuf validation

    main

    The realtimemap example utilizes protoc-gen-validate (PGV) to perform automated validation of Protobuf messages. PGV allows you to define validation rules directly within your .proto files, which are then used to generate validation code in your target language. This ensures that incoming requests or data structures adhere to specific constraints (like string length, integer ranges, or regex patterns) before they reach your business logic.

    For full documentation and installation instructions, refer to the official repository: https://github.com/envoyproxy/protoc-gen-validate