go-kratos/examples
repository·main·Indexed 19 days ago
https://github.com/go-kratos/examplesA 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.
What's inside go-kratos-examples
- 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.
Overview of kratos-chatroom
mainThekratos-chatroomexample 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.Overview of kratos-realtimemap
mainThe
kratos-realtimemapproject 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.
Overview of the Logger Job service
mainThe Logger Job is a log writing service designed to consume messages from Kafka and persist them into a database. It serves as a consumer component within the CQRS (Command Query Responsibility Segregation) architecture pattern demonstrated in this example.Overview of kratos-cqrs
mainThe
kratos-cqrsproject 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-transportto provide support for Kafka, RabbitMQ, MQTT, Redis, Websocket, and NATS.The architecture is split into two primary microservices:
- Log Query Service (
kratos.logger.service): Provides a gRPC interface for querying logs and uses theEntgoORM to perform time-series queries against TimeScaleDB. - Log Write Service (
kratos.logger.job): A background worker that connects to Kafka and subscribes to specific topics to persist data.
- Log Query Service (
Explore Kratos feature examples
mainThe
go-kratos/go-kratos/examplesrepository 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).
- JWT: Using JSON Web Tokens for authentication (
Implement sessions using gorilla/sessions and go-redis
mainThis example demonstrates how to implement thesessions.Storeinterface by combininggorilla/sessionswithgo-redis/v8. It is designed to be used as a Kratoshttp.Transportto manage user sessions via Redis.Explore Kratos examples
mainThe
examplesrepository 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 viaproto-gen-go-errors.log: Provides examples forlogger,helper,filter, andvaluer.metadata: Demonstrates usage of metadata.registry: Shows service registration and discovery usingEtcd,Consul, andNacos.validate: Demonstrates middleware-based validation using code generated byproto-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
Kafka Client Selection for CQRS Job Data
mainWhen 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 theOutOfRangemechanism may cause the client to re-consume all messages from the beginning if the client crashes or the server version is upgraded.
Kafka Client Selection in CQRS Example
mainIn the
cqrs/app/logger/serviceimplementation, 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:
- Partition Awareness: Sarama cannot detect when new partitions are added to a Topic without a client restart.
- Multi-Topic Subscription: Subscribing to two or more Topics simultaneously in Sarama 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 custom implementation of theOutOfRangemechanism 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.
Understand the AuthN and AuthZ implementation in kratos-casbin
mainThe
kratos-casbinexample 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, anduser), though the implementation demonstrates permission limiting via usernames.Use protoc-gen-validate (PGV) for Protobuf validation
mainThe
realtimemapexample utilizesprotoc-gen-validate(PGV) to perform automated validation of Protobuf messages. PGV allows you to define validation rules directly within your.protofiles, 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