简体中文 | English (this page)
Lucky-Cloud is a high-performance and highly available instant messaging (IM) backend built on Spring Cloud Alibaba +
Spring Boot 3.
The system adopts a microservice architecture, supports massive concurrent connections, and provides a complete IM
solution including message delivery, audio/video calls, and file transfer.
- Java 21: Leverages the latest language features for performance and security
- Spring Boot 3.5.9: Native support for JDK 21, optimized for containerized deployment
- Spring Cloud Alibaba 2025: Full microservice governance
- MyBatis Plus: ORM framework on top of MyBatis
- Apache Dubbo: RPC across microservice modules
- Apache Seata: Distributed transaction management
- Google ProtoBuf: Efficient serialization protocol
- Netty: Asynchronous networking for long connections
- RabbitMQ: High-availability, high-throughput message queue integration
- MinIO: Object storage for file upload/download/management
- Microservice architecture: Modular design with independent deployment and scaling
- High concurrency: WebSocket long connections for large-scale concurrency
- Instant messaging: Text, images, audio, video, and files
- Group chat: Full group management; auto-generated group avatars
- Audio/Video calls: WebRTC + SRS for 1:1 and group calls
- Message push: Real-time push with offline message storage
- File transfer: Backed by MinIO
- Authentication: JWT token mechanism
- Password encryption: RSA public-key cryptography
- Access control: Fine-grained permissions
- Data security: Sensitive data encrypted at rest
- High availability: Service discovery, load balancing, circuit breaking/fallback
- Scalability: Horizontal scaling, dynamic capacity expansion
- Monitoring & alerts: Sentinel integration for real-time monitoring
- Configuration: Dynamic config with hot updates
- Dynamic data source: Add/remove/switch data sources with health checks
Entry point for routing, load balancing, rate limiting, and circuit breaking
- Integrates Sentinel for rate limiting and load balancing
- Service discovery/registry via Nacos; dynamic routing
- Routes long-connection requests based on user info in Redis
- Global signing verification, JWT authentication, blacklist interception, and dynamic fallback filters
User authentication and authorization
- Login/register/token generation and validation
- Provides RSA public key for password encryption during login
- SMS verification service
- Multi-strategy authentication: username/password, SMS login, QR-code scanning
WebSocket long-connection management and message delivery
- Manages client long connections with heartbeat
- Consumes messages from RabbitMQ and pushes to users
- Multi-instance deployment with automatic load balancing
- Connection limiter and message rate limiter, monitoring/logging, and virtual-thread optimizations
Core business logic
- Send/receive/store/query messages
- Group management, file upload, group avatar generation
- Dispatch messages to the corresponding
im-connectinstance - Concurrency control using Redisson and Redis caching for hot data
im-ai(port:8088): AI services (chat, embeddings, prompt management, tool calling)im-file(port:8087): MinIO-based file service supporting chunked upload, resume, image compression/thumbnail/watermark, NSFW image moderationim-platform(port:8090): Platform service (app updates and short links) with version check, presigned downloads, Bloom dedup + Caffeine LRU + Redis cachingim-leaf(port:8086): Distributed ID generation (Segment, Snowflake, UID, UUID) with Nacos worker-id allocationim-database(port:8100): DB initializer and metadata serviceim-meet(WebSocket19100): Real-time meeting/chat service (Netty WS)im-analysis(port:8089): Text analysis (HanLP segmentation, keywords, dependency parsing)im-proxy: Nginx config templating to assist WS proxy and load balancingim-framework: Base aggregation (core/domain/common/crypto/spring/grpc/security/mq)
User sending flow:
1. Client → im-gateway → im-server
2. im-server handles business logic
3. im-server → RabbitMQ → im-connect
4. im-connect → user long connection → client
Long-connection management:
1. Client establishes WebSocket via im-gateway
2. im-connect registers user info and machine code in Redis
3. Heartbeats maintain connection state
4. On disconnect, related Redis records are cleaned up
Client → im-gateway → im-server → RabbitMQ → im-connect → Client
- Build message DTO (
messageIdglobally unique; Snowflake or UUID recommended;messageTempIdclient-side only). - Persist message + write outbox (same transaction):
- Insert into message table (
im_private_message/im_group_message) and anoutboxrecord (storemessageId/payload/targetBroker/status).
- Insert into message table (
- Commit transaction (DB commit means the message is reliably saved).
- Attempt to publish to RabbitMQ (read from outbox or publish immediately):
- Use Publisher Confirms (
channel.confirmSelect()) andmandatoryflag to ensure broker reception and persistence. - If confirm
ack, mark outboxSENT_TO_BROKER. - If publish fails or no confirm, keep status
PENDING; background job retries.
- Use Publisher Confirms (
- Background compensation job: Periodically scan outbox
PENDING/FAILEDand retry or escalate.
- Set exchange/queue to durable
- Publish with
persistent=true - Use publisher confirms (lighter and recommended over transactions)
- Consider quorum queues or mirrored/clustered setups
- Configure dead-letter-exchange (DLX) for failed/unroutable messages
- On consume, ack appropriately (process-first or persist-first as designed; guarantee no loss):
- Persist then
ack; or - Use manual ack: on success
ack, on failurenack/reject(requeue or DLX)
- Persist then
- Idempotency: Check whether delivered (by
messageIdin a delivery/status table); ignore duplicates - Route to client: Find the user’s WebSocket connection (from Redis registry) and push
- Client ACK (optional but recommended):
- Client returns
DELIVERY_ACK(messageId)toim-connect im-connectupdates DB (or callback toim-server) to mark asDELIVERED- If no ACK, retry several times then mark
UNDELIVEREDand trigger policy/alerts
- Client returns
- On receipt, send ACK, persist locally, update UI, and deduplicate by
messageId
- Java 21: Runtime
- Spring Boot 3.2.4: Application framework
- Spring Cloud Alibaba 2023.0.0.0-RC1: Microservice framework
- Spring WebFlux: Reactive web framework
- MyBatis Plus: Persistence layer
- Netty: Server-side long connections
- Nacos: Service discovery and configuration management
- Redis: Cache/session management
- RabbitMQ: Message queue, async communication
- MinIO: Object storage
- SRS: Streaming/WebRTC support
- Docker: Containerization
- Nginx: Reverse proxy/load balancer
- JDK 21: Java runtime
- JDK: 21.0.0+
- Docker: 20.10.0+
- Docker Compose: 2.0.0+
- OS: Linux/Windows/macOS
Recommendation: Deploy on Linux for best performance.
# Redis
docker run --name redis -p 6379:6379 -v /root/redis/conf/redis.conf:/usr/local/etc/redis/redis.conf -d redis --appendonly yes
# Nacos
docker run -itd --name nacos --env PREFER_HOST_MODE=hostname --env MODE=standalone --env NACOS_AUTH_IDENTITY_KEY=serverIdentity --env NACOS_AUTH_IDENTITY_VALUE=security --env NACOS_AUTH_TOKEN=SecretKey012345678901234567890123456789012345678901234567890123456789 -p 8848:8848 -p 9848:9848 -p 9849:9849 nacos/nacos-server:v2.2.1
# RabbitMQ
docker run -d --hostname my-rabbit --name rabbit -p 15672:15672 -p 5671-5672:5671-5672 rabbitmq
docker exec -it rabbit /bin/bash
rabbitmq-plugins enable rabbitmq_management
# MinIO
docker run -p 9000:9000 -p 9090:9090 --name minio -d --restart=always -e "MINIO_ACCESS_KEY=minioadmin" -e "MINIO_SECRET_KEY=minioadmin" -v /root/minio/data:/data -v /root/minio/config:/root/.minio minio/minio server /data --console-address ":9090" --address ":9000"
# SRS (Set CANDIDATE to your host IP)
docker run -it -p 1935:1935 -p 1985:1985 -p 8080:8080 -p 1990:1990 -p 8088:8088 --env CANDIDATE=192.168.1.9 -p 8000:8000/udp registry.cn-hangzhou.aliyuncs.com/ossrs/srs:6.0-d2
# PostgreSQL
docker run -d --name postgres -p 35432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres -v D:/Docker-vm/postgresql/vectordata:/var/lib/postgresql/data ankane/pgvector# application.yml sample
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yml
redis:
host: localhost
port: 6379
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
# MinIO
minio:
endpoint: localhost:9000
accessKey: minioadmin
secretKey: minioadmin
bucket: im-files
# SRS
srs:
webrtc: http://localhost:8080
rtmp: rtmp://localhost:1935Two approaches:
Manual order
1. im-database (port: 8086)
2. im-auth (port: 8084)
3. im-server (port: 8085)
4. im-connect (ports: 19000–19002)
5. im-gateway (port: 9191)
6. im-leaf (port: 8086)Build scripts
# Windows
deploy-all.bat
# Linux/macOS
./deploy-all.sh- Gateway: http://localhost:9191
- Auth: http://localhost:8084
- Business: http://localhost:8085
- File: http://localhost:8087
- ID: http://localhost:8086
- AI: http://localhost:8088
- Analysis: http://localhost:8089
- Platform: http://localhost:8090
- Nacos Console: http://localhost:8848/nacos (nacos/nacos)
- RabbitMQ Management: http://localhost:15672 (guest/guest)
- MinIO Console: http://localhost:9090 (minioadmin/minioadmin)
- SRS: http://localhost:8080
- PostgreSQL: localhost:35432
- Connect WebSocket: ws://localhost:19000/im, ws://localhost:19001/im, ws://localhost:19002/im
- Meet WebSocket: ws://localhost:19100
├── im-server/ # business service
├── im-gateway/ # API gateway
├── im-auth/ # authentication service
├── im-connect/ # connection service (WebSocket)
├── im-leaf/ # ID generation service
├── im-file/ # file management service
├── im-platform/ # platform service
├── im-framework/ # base framework aggregation
│ ├── im-core/ # core utilities
│ ├── im-domain/ # domain models
│ ├── im-general/ # common components
│ ├── im-grpc/ # gRPC
│ ├── im-security/ # security
│ ├── im-spring/ # spring extensions
│ └── im-common/ # utility libraries
└── docs/ # documentation
- Follow Alibaba Java Development Manual
- Unified code formatting
- Comprehensive documentation
- Unit test coverage > 80%
After services are up:
- Swagger UI: http://localhost:8085/doc.html
- OpenAPI: http://localhost:8085/v3/api-docs
# Unit tests
mvn test
# Integration tests
mvn verify
# Coverage report
mvn jacoco:report# Build images
mvn clean package -DskipTests
# Deploy all services with Docker Compose
docker-compose up -d- Use Nginx for reverse proxy and load balancing
- Configure SSL certificates for HTTPS
- Tune JVM parameters
- Set up logging, monitoring, and alerting
- Concurrent connections: 10,000+ WebSocket connections
- Message latency: Average < 100ms
- Throughput: 10,000+ TPS
- Response time: 99% < 200ms
Test environment: 8-core/16GB cloud server, JDK 21, Docker deployment
- New modules
im-file: Image processing (compression, thumbnails, watermark), chunk/resume uploads, MD5 validation, NSFW image moderationim-platform: App updates and short links (Bloom dedup, Caffeine LRU, Redis caching, layered visit-count aggregation)im-leaf: Multiple ID strategies with Nacos worker-id allocationim-ai: Spring AI integration (chat/embeddings/tools), improved prompt/session managementim-analysis: Text analytics: segmentation/keywords/dependency parsingim-proxy: Nginx proxy template generation and maintenanceim-meet: Netty-based real-time meeting service (WebSocket)
- Gateway enhancements
- Global signing, JWT auth, blacklist, dynamic fallback filters, route caching (
im-gateway)
- Global signing, JWT auth, blacklist, dynamic fallback filters, route caching (
- Connection service enhancements
- Connection/message rate limiter, monitoring, virtual-thread optimization, improved message pipeline (
im-connect)
- Connection/message rate limiter, monitoring, virtual-thread optimization, improved message pipeline (
- Business service optimizations
- Redisson-based locks, Redis hot cache, idempotency improvements, and performance logging across group/user
operations (
im-server)
- Redisson-based locks, Redis hot cache, idempotency improvements, and performance logging across group/user
operations (
- File service fixes
- Fix MinIO client signing issue and improve stability (
im-filePearlMinioClient.java)
- Fix MinIO client signing issue and improve stability (
We welcome all contributions! See CONTRIBUTING.md for details.
- Fork the project
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add some AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Open issues to report problems or request features
- Join the tech community for discussion
- Project Home: https://github.com/LucklySpace/Lucky-cloud
- Issues: Issues
This project is for learning and reference only and must not be used for commercial purposes. The author is not responsible for any direct or indirect loss caused by the use of this project.
- Open-source learning project for IM technology study and research
- Technical schemes and code are for reference only; no guarantee for production stability/security/reliability
- Users assume all risks (including data loss, system damage, communication security, etc.)
- No warranty or support is provided, and no guarantees for outcomes
- Commercial use is at your own legal risk and responsibility
Actively maintained with continuous updates and improvements.