# bytech-cloud
**Repository Path**: nbytech/bytech-cloud
## Basic Information
- **Project Name**: bytech-cloud
- **Description**: No description available
- **Primary Language**: Java
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 8
- **Forks**: 4
- **Created**: 2026-06-23
- **Last Updated**: 2026-10-28
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# javatech-cloud
A **SaaS Multi-Tenant Platform** built on Spring Cloud microservices architecture, supporting one-click switching between **microservice** and **monolith** deployment modes.
## Screenshots
| | |
|---|---|
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  | |
## Core Features
| Feature | Description |
|---------|-------------|
| **Dual-Login Switching** | Two independent identity systems: Platform Admin + Tenant User, switch freely without interference |
| **Multi-Tenant Data Isolation** | Lightweight Schema-level isolation per tenant via MySQL `USE database` |
| **Microservice / Monolith Dual Mode** | `monolith` Profile aggregates all modules; zero network overhead for Feign in monolith mode |
| **RBAC Permission** | Dual RBAC hierarchies (Platform + Tenant), `@PreAuth` method-level access control |
| **Audit Logging** | Level-3 compliance: `@OperLog` + `@DataChangeLog` + HTTP access log |
| **File Service** | Upload/batch-upload/download/preview/thumbnail, local + multi-cloud storage (OSS/COS/MinIO/Qiniu/OBS/S3) |
| **System Monitoring** | Service monitoring (SBA: CPU/memory/JVM/GC + dynamic log level), Redis monitoring, online users |
| **IP Blacklist** | API + Gateway dual-layer interception |
| **Code Generator** | MyBatis-Plus code generation: Controller/Service/Mapper/Entity |
| **AI Chat** | Multi-channel routing across 8 AI platforms (OpenAI/DeepSeek/GLM/ERNIE/Hunyuan/Kimi/Qwen/Ollama) + channel management + conversation history |
| **Scheduled Tasks** | XXL-JOB based distributed scheduling: task management / execution logs / microservice distributed + monolith dual-mode |
| **Login Captcha** | Unified pluggable captcha system: Image / SMS / TOTP types with independent on/off switches, strategy pattern + SPI decoupling, web + uniapp frontends integrated |
| **WAF (Web Application Firewall)** | In-app WAF: dual-mode (Gateway / Servlet) detection, SQLi / XSS / path-traversal / command-injection / scanner-fingerprint detection, canary rollout, attack-log persistence, lightweight observation of non-business URLs / suspicious params / failed logins |
## Tech Stack
| Category | Technology | Version |
|----------|-----------|---------|
| Framework | Spring Boot + Spring Cloud + Spring Cloud Alibaba | 3.2.5 / 2023.0.1 |
| Registry/Config | Nacos | 2.3.2 |
| Gateway | Spring Cloud Gateway (WebFlux) | 4.1.x |
| Database | MySQL | 8.0 |
| Connection Pool | Druid | 1.2.20 |
| ORM | MyBatis-Plus + dynamic-datasource | 3.5.5 / 4.2.0 |
| Auth | Sa-Token (Dual StpLogic) + JWT | 1.37.0 |
| RPC | OpenFeign + LoadBalancer | 4.1.1 |
| Cache | Redis + Redisson | 7.x |
| API Doc | Knife4j (OpenAPI 3.0) | 4.4.0 |
| Object Mapping | MapStruct | 1.5.5 |
| Utilities | Hutool | 5.8.24 |
| IP Geolocation | ip2region (offline) | 3.3.7 |
| AI Chat | LangChain4j | 0.35.x |
| Scheduled Tasks | XXL-JOB | 2.4.0 |
| Java | JDK 17 | - |
## Module Structure
```
javatech-cloud
├── bytech-common Common modules
│ ├── bytech-common-core Core: R, exceptions, constants, TenantContextHolder
│ ├── bytech-common-security-core Security core: whitelist, IP blacklist, WAF detection core (no web deps)
│ ├── bytech-common-security Security: @PreAuth, LoginUser, dual StpLogic config
│ ├── bytech-common-log Logging: @OperLog / @DataChangeLog / Access Log
│ ├── bytech-common-web Web: global exception handler, Jackson, Knife4j
│ ├── bytech-common-redis Redis: serialization, caching, distributed lock
│ ├── bytech-common-mybatis MyBatis: pagination, auto-fill, dynamic-datasource, Druid
│ └── bytech-common-tenant Multi-tenant: schema interceptor, header extraction, Feign forwarding
├── bytech-feign-api Feign API aggregation
│ ├── bytech-feign-api-system System service API
│ ├── bytech-feign-api-platform Platform service API
│ ├── bytech-feign-api-file File service API
│ └── bytech-feign-api-ai AI service API (chat/channel remote calls)
├── bytech-gateway Spring Cloud Gateway
├── bytech-auth Authentication service (login/logout/permission loading)
├── bytech-monitor System monitoring (service monitor SBA / Redis monitor / online users)
├── bytech-modules Business modules
│ ├── bytech-system Tenant system (users/roles/menus/depts/dicts/logs/config)
│ ├── bytech-platform Platform admin (tenant CRUD/plans/platform RBAC)
│ ├── bytech-file File service (upload/download/preview/multi-cloud storage)
│ ├── bytech-ai AI intelligence (multi-channel chat / channel management / conversation history)
│ ├── bytech-job Scheduled tasks (XXL-JOB distributed scheduling / task management / execution logs)
│ └── bytech-waf WAF: attack-log consumer / admin (planned)
└── bytech-boot Monolith launcher module
```
## Dual-Login Switching
Platform admins and tenant users have **completely independent identity systems**, sharing the same frontend, online simultaneously, switchable at any time.
```
┌─────────────────────────────────────────────────────┐
│ Platform Admin (loginType="platform") │
│ Path: /platform/* StpLogic: platformStpLogic │
│ Token Redis Key: platform:token:xxx │
│ Database: bytech_platform (global singleton) │
├─────────────────────────────────────────────────────┤
│ Tenant User (loginType="auth") │
│ Path: /system/* StpLogic: stpLogic (primary) │
│ Token Redis Key: auth:token:xxx │
│ Database: bytech_system_{tenantCode} (one per tenant)│
└─────────────────────────────────────────────────────┘
```
- Two `StpLogic` instances share the same Redis connection, Key-isolated via different `loginType`, **can be online simultaneously without conflict**
- Frontend stores both tokens in `localStorage`, `currentLoginType` in `sessionStorage` (per-tab isolation)
- Auto-switches to the other logged-in identity on logout
> Detailed docs: [docs/双系统同时登录机制.md](docs/双系统同时登录机制.md) (Chinese)
## Multi-Tenant Data Isolation
**Schema-level isolation** — each tenant gets an independent MySQL database, lightweight and efficient.
```
HTTP Request (Authorization: Bearer {token})
│
├─ Gateway AuthFilter
│ └─ Read LoginUser from Redis TokenSession → tenantCode
│ └─ Write trusted Tenant-Code Header (strip external forgery attempt first)
│
├─ TenantHeaderInterceptor (Servlet Filter)
│ └─ Header → TenantContextHolder (TransmittableThreadLocal)
│
└─ TenantSchemaInterceptor (MyBatis Plugin)
└─ USE bytech_system_{tenantCode} before each SQL
└─ No tenantCode → fallback USE bytech_system
```
| Component | Location | Role |
|-----------|----------|------|
| `TenantContextHolder` | `bytech-common-core/.../holder/` | Thread-safe context via TransmittableThreadLocal |
| `TenantHeaderInterceptor` | `bytech-common-tenant/.../interceptor/` | Extract from Header & set context |
| `TenantSchemaInterceptor` | `bytech-common-tenant/.../interceptor/` | MyBatis Plugin, dynamic USE before SQL |
| `TenantFeignInterceptor` | `bytech-common-tenant/.../interceptor/` | Forward tenant info during Feign calls |
| `TenantCodeResolver` | `bytech-common-security/.../utils/` | Parse tenantCode from Token or Session |
**DataSource Design**:
- `tenant` datasource (primary): shared connection pool, `USE` switches dynamically, zero overhead
- `platform` datasource: `@DS("platform")` annotation switch, fixed `bytech_platform` connection
**Pluggable**: Multi-tenant module is completely inactive if `bytech-common-tenant` is not on the classpath.
## Microservice / Monolith Dual Mode
One-click switch via `monolith` Profile; in monolith mode, Controller Beans are injected directly instead of Feign HTTP calls.
| Mode | Profile | Nacos | Feign | Launch |
|------|---------|-------|-------|--------|
| **Microservice** | `dev`/`prod` | ✅ Enabled | ✅ HTTP proxy | Start each service |
| **Monolith** | `monolith` | ❌ Disabled | ❌ Local injection | Start `bytech-boot` only |
```bash
# Monolith mode (one-click start)
mvn clean package -pl bytech-boot -DskipTests
java -jar bytech-boot/target/bytech-boot-exec.jar --spring.profiles.active=monolith
# Microservice mode (requires Nacos running first)
# Start in order: gateway → auth → system → platform → file → ai → monitor
```
**Monolith Mode Design**:
- `bytech-boot` aggregates all modules; `@ComponentScan("com.bytech")` full scan
- `SecurityConfig` (`@Profile("monolith")`): Servlet interceptor chain (no Gateway dependency)
- Controller `implements FeignClient`; `@Autowired` injects local Bean directly, zero network overhead
> Detailed docs: [docs/API_CALLING_CONVENTION.md](docs/API_CALLING_CONVENTION.md) (Chinese)
## Audit Logging
Level-3 compliance audit solution with three logging dimensions:
| Type | Trigger | Table | Description |
|------|---------|-------|-------------|
| **Operation Log** | `@OperLog` | `sys_oper_log` / `platform_oper_log` | CRUD business operations |
| **Data Change** | `@DataChangeLog` | `sys_data_change_log` | Old-vs-new value diff comparison |
| **Access Log** | Global interceptor | `sys_access_log` / `platform_access_log` | Full HTTP request audit |
**Access Log Architecture**:
```
Monolith: AccessLogInterceptor (Servlet) → AsyncLogService → Feign → Controller → DB
Microservice: AccessLogGatewayFilter (Gateway) → WebClient POST → Controller → DB
```
Log tables are protected by database triggers preventing UPDATE/DELETE — immutable for compliance.
## System Monitoring
The `bytech-monitor` module provides service monitoring, Redis monitoring, and online user management — available in both microservice and monolith modes.
| Capability | Description |
|------------|-------------|
| **Service Monitor** | Based on Spring Boot Admin, aggregates CPU / memory / JVM / GC metrics per service, with instance detail, health check, and dynamic log level; dual-mode (microservice / monolith) |
| **Redis Monitor** | Direct Redis connection: connection count, hit rate, memory usage, slow log, clients, command stats, and performance trends in real-time |
| **Online Users** | Real-time online user list with forced logout |
**Dual-mode design**: `/monitor/instance/*` is the unified entry, switching implementation via the `ServerMonitorService` interface with `@Profile` — microservice mode (`!monolith`) aggregates via SBA, monolith mode (`monolith`) reads the local Actuator directly; frontend unchanged.
> Detailed docs: [docs/system-monitoring.md](docs/system-monitoring.md) (Chinese)
## WAF (Web Application Firewall)
A self-built **in-app WAF** using a "Spring Cloud Gateway (WebFlux `GlobalFilter`) + Boot (Servlet `Filter`) dual-mode" architecture. The detection core is sunk into `bytech-common-security-core` and **reused on both ends**; it covers rule groups such as SQL injection / XSS / path traversal / command injection / SSRF / scanner fingerprints / protocol compliance, and supports **canary rollout (observe-only)**, **four-level switches**, **fault isolation (fail-open)**, and **lightweight security observation**.
> Full design (architecture, sequence diagrams, rule list, Redis conventions, phased roadmap): [docs/waf-design.md](docs/waf-design.md) (Chinese)
### Core Capabilities
| Capability | Description |
|------------|-------------|
| **Dual-mode detection** | Gateway-side `WafGatewayFilter` (`order = -300`) and monolith-side `WafServletFilter` share the `bytech-common-security-core` detection core; rules / thresholds / switches are one shared config, zero duplicated code |
| **Rule groups** | `SQLI` (SQL injection) / `XSS` / `PATH` (path traversal) / `CMD` (command injection, SSRF) / `SCANNER` (scanner fingerprints, e.g. `curl`, `sqlmap`) / `PROTO` (protocol compliance) |
| **Canary rollout** | `action: OBSERVE` (log only, no block) → observe period with no false positives → `BLOCK` (intercept); low-risk go-live |
| **Four-level switches** | Master `waf.enabled` → assembly `waf.servlet-filter.enabled` → behavior (observe-only) → per-rule-group switch, with Nacos hot-reload |
| **Fault isolation (fail-open)** | Filter / rule exceptions always pass through and alert; WAF's own failure never impacts business; degrades to no persistence when Redis is unavailable |
| **Attack-log persistence** | Hits go through Redis queue `waf:log:queue` → `WafAttackLogConsumer` → `waf_attack_log`, sharing the same table and dashboard with lightweight observation |
| **Lightweight observation (done)** | Non-business URLs (`[NON-BUSINESS-URL]`), suspicious params (`[SUSPECT-PARAM]`), and failed logins (`[AUTH-FAIL]`) are persisted to `waf_attack_log` via `ObserveAttackLogPublisher`, distinguished from real attacks by `rule_group` (`OBSERVE` / `AUTH-FAIL`); no new table |
| **Dynamic rate-limit / ban (P1)** | Count hits per IP / UA / session with sliding-window rate limiting and temporary bans (`WafRateLimiter` interface defined, in progress) |
| **Admin console / attack map (P2)** | Security overview, attack-log query, ban management, custom rules, real-time attack map, risk reports (planned) |
### Dual-mode architecture
```
Request
├─ Microservice: Gateway → WafGatewayFilter (WebFlux, order=-300) → AuthFilter → routing
└─ Monolith: Servlet container → WafServletFilter → business Controller
↓ shared
bytech-common-security-core: WafDetector (rule matching) + WafRuleProvider (rule loading / hot-reload)
↓ hit
waf:log:queue (Redis List) ← WafRedisSyncLogSink
↓ consume
WafAttackLogConsumer (bytech-waf module) → waf_attack_log (bytech_system DB)
```
### Lightweight observation persistence (done)
Four classes of security events all land in `waf_attack_log`, distinguished from real attacks by `rule_group`:
| rule_group | rule_id | Trigger | severity |
|------------|---------|---------|----------|
| `OBSERVE` | `OBSERVE-URL` | 404 non-business URL (`GlobalExceptionHandler.handleNoResourceFound`) | 2 |
| `OBSERVE` | `OBSERVE-PARAM` | Suspicious params on real endpoints (`SecurityObserveFilter`, read-only, log-only) | 2 |
| `AUTH-FAIL` | `LOGIN-BAD-CRED` / `LOGIN-DISABLED` / `LOGIN-LOCKED` / `LOGIN-TENANT` | Failed login (`AuthController`, account locked = 3, others = 2) | 2 / 3 |
### Implementation phases
- **P0 (done)**: detection core + dual-mode filters + rule set + four-level switches + canary rollout + fault isolation + lightweight observation persistence;
- **P1 (in progress)**: attack-log persistence (`WafAttackLogConsumer` already implemented), dynamic rate-limit / ban;
- **P2 (planned)**: admin console, real-time attack map, risk reports, custom-rule UI.
### Key config (Nacos / `application.yml`)
| Config | Default | Description |
|--------|---------|-------------|
| `waf.enabled` | `true` | Master switch |
| `waf.servlet-filter.enabled` | microservice `false` / monolith `true` | Monolith-side assembly switch (gateway side always on) |
| `waf.rules.default.action` | `OBSERVE` | Default behavior: `OBSERVE` (observe-only) / `BLOCK` (intercept) |
| `waf.observe.exclude-ips` / `waf.observe.exclude-paths` | loopback, `/actuator/health` | Lightweight-observation exclusions (local / health-check traffic not logged) |
## Roadmap (TODO)
Features with **✅ Completed** below are ready to use; the rest are planned for the next phase.
### System Monitoring
| Feature | Status | Description |
|---------|--------|-------------|
| ✅ Service Monitor | **Completed** | Spring Boot Admin — CPU, memory, JVM, GC per service; instance detail, health check, dynamic log level; microservice / monolith dual mode |
| ✅ Redis Monitor | **Completed** | Connection count, hit rate, memory usage, slow log, clients, command stats, performance trends in real-time |
| ✅ Online Users | **Completed** | Real-time online user list with forced logout |
| ✅ Scheduled Tasks | **Completed** | XXL-JOB based distributed scheduling: task management / execution logs / microservice distributed + monolith dual-mode |
### File Service
| Feature | Status | Description |
|---------|--------|-------------|
| ✅ Local / Multi-Cloud Storage | **Completed** | Local disk + Alibaba OSS + Tencent COS + MinIO + Qiniu + Huawei OBS + S3, config-based switching |
| ✅ Upload / Download / Preview | **Completed** | Single upload, batch upload, download, image preview, thumbnail, access URL resolution |
| Resumable Transfer | Planned | Chunked upload for large files with pause/resume support |
| File Watermark | Planned | Dynamic watermarking for images/PDFs, anti-leak tracing |
### Developer Tools
| Feature | Status | Description |
|---------|--------|-------------|
| ✅ Open API | **Completed** | Swagger / Knife4j online debug, auto-grouped API docs per service |
| Code Generator | Planned | Online generation: Controller / Service / Mapper / Entity / Vue pages |
| Online Form | Planned | Visual drag-and-drop form designer, dynamic CRUD pages |
| Workflow | Planned | Flowable workflow engine, visual process design |
### Agreement Management
Unified management and cross-platform display of related agreements (user agreement, privacy policy, etc.) for the Web and Uniapp ends. **Current scope**: agreement content management + cross-platform display; version management, user consent logs, mandatory-update prompts, etc. are scheduled for later iterations.
| Feature | Status | Description |
|---------|--------|-------------|
| Agreement Type Management | Planned | Built-in common agreement types (`agreement_type`), with type extension and customization |
| Agreement Content Management | Planned | Rich-text agreement content editing, maintained in the web admin, read-only display on both ends |
| Built-in Seed Agreement Types | Planned | Preloaded: User Service Agreement, Privacy Policy, Children's Privacy Protection Guide, Cookie Policy, Third-Party Sharing List, Membership/Paid Service Agreement, Account Deactivation Agreement, Disclaimer, Developer/Open Platform Agreement, Minor Protection |
| Web Admin Management | Planned | bytech-ui dynamic menu adds an "Agreement Management" page, CRUD for agreement types and content |
| Uniapp Display | Planned | Agreement links in register / login checkboxes, agreement list under Settings-About, opening agreement detail page (rich-text rendering) |
| Cross-Platform Content Consistency | Planned | Web and Uniapp share the same agreement data source (`system/agreement` API in the bytech-system module) |
**Implementation location**: new Agreement Controller/Service/Mapper/Entity in the backend `bytech-system` module (reusing the notice rich-text + `@PreAuth` permission pattern); a dynamic-menu admin page in the web UI; agreement display pages wired into register / login / Settings-About on the Uniapp end.
### AI Features
#### ✅ Completed: AI Chat Module
| Feature | Description |
|---------|-------------|
| AI Chat | ChatGPT-style interface: multi-turn chat, conversation history switch/delete, channel & model selection |
| AI Channel Management | CRUD for 8 AI platforms: OpenAI, DeepSeek, GLM, ERNIE, Hunyuan, Kimi, Qwen, Ollama; AES-encrypted API keys |
| Multi-Channel Routing | Route by `channelCode` or enabled priority; model instances cached & reused by `channel:model` |
| Conversation History | Isolated per user, persisted to `ai_conversation` / `ai_message`, supports continuing with context |
| Feign Remote Call | `bytech-feign-api-ai` exposes `AiChatFeignClient` for other services |
#### Planned
| Feature | Description |
|---------|-------------|
| Smart Assistant | LLM integration — natural language data query & report generation |
| Code Review | AI-assisted code review, auto-detect conventions & security issues |
| Intelligent Log Analysis | Auto-cluster exceptions, alerting, fix suggestions |
| Compliance Check | AI audit of operation logs, anomaly behavior detection |
| Streaming Output | SSE streaming for typewriter effect |
### Security Enhancement
The login captcha uses a **unified pluggable architecture** (`CaptchaManager` dispatcher + `CaptchaProvider` strategy + `CaptchaStorage` / `CaptchaConfigReader` / `SmsSender` / `TotpSecretResolver` SPI decoupling). All types are centrally configured in `sys_config`, **disabled by default**, freely combinable and hot-switchable; the frontend dynamically renders and assembles parameters based on the `/auth/captcha/config` response.
#### Three captcha switches & params (`sys_config`)
| Type | Switch key | Description | Key params (defaults) |
|------|------------|-------------|----------------------|
| Image image | `security.captcha.image.enabled` | AWT-rendered (digits / arithmetic / Chinese arithmetic), returns `key` + `imageBase64`, zero extra dependency | TTL `image.expire` (120s), type `image.type` (number/char) |
| SMS sms | `security.captcha.sms.enabled` | 6-digit code via `SmsGateway` (Aliyun/Tencent, config-switchable) | TTL `sms.expire` (300s), send interval `sms.interval` (60s) |
| TOTP totp | `security.captcha.totp.enabled` | RFC 6238 (self-implemented HMAC-SHA1 + Base32, no third-party dependency), compatible with Google Authenticator | 30s window, ±1 step tolerance |
#### Verification timing & contract (login `LoginDTO`)
- Login payload carries `captchaType` (`image`/`sms`/`totp`), `captchaKey`, `captcha`; `captchaKey` = image:`uuid`, sms/totp: login account (backend resolves the bound phone/TOTP secret from the account).
- **SMS**: enforced when enabled; the destination number is strictly the user table `phone` field (resolved from the account, the frontend never enters a phone number).
- **TOTP**: required only when the user has bound it (prevents bound users from bypassing); unbound users pass through. Returns `totpBound` (`true` bound & verified / `false` unbound / `null` disabled) so the frontend can prompt binding.
- **Image**: verified only when the frontend selects that type; an empty `captchaType` skips captcha verification.
#### Other security capabilities
| Feature | Description |
|---------|-------------|
| IP rate limit / replay | Image captcha: IP-level rate limiting + one-time consumption; SMS: configurable send interval / expiry, anti-spam / anti-SMS-bombing |
| TOTP secret safety | AES-encrypted secret storage, second-factor verification after binding |
| IP Black/Whitelist Management | Visual configuration of IP whitelist / blacklist, effective at module / API level, supporting CIDR ranges and scheduled allow / block |
| Login failure lockout | Lock the account after `MAX_FAIL_COUNT=5` consecutive failures (`ACCOUNT_LOCKED` logic in `AuthController`) |
| Login audit log | IP, UA, geo, port, fail reason, fail count, login type, tenant code, asynchronously written to `sys_login_log` / `pf_login_log` via Feign |
| Dual token isolation | Platform-admin and tenant-user tokens use dual `StpLogic` (`loginType` = `platform` / `auth`), isolated by Redis key prefix, both online simultaneously |
> Design and implementation details (architecture, sequence, Redis key conventions): [docs/captcha-design.md](docs/captcha-design.md)
### IP Geolocation
Integrated ip2region 3.x offline database — no internet required, microsecond-level resolution.
**Enable**: Place `ip2region_v4.xdb` / `ip2region_v6.xdb` in `bytech-common/bytech-common-core/src/main/resources/ipdb/`
Download: [ip2region data](https://github.com/lionsoul2014/ip2region/tree/master/data)
> When database files are absent, IP lookup is automatically disabled, returning "Unknown" without affecting normal operations.
## Docker Deployment
The `docker-bytech/` directory ships a Docker Compose orchestration file supporting both **microservice** and **monolith** deployment modes out of the box.
### Directory Layout
```
docker-bytech/
├── docker-compose.yml # Orchestration (microservices / monolith by profile)
├── .env / .env.example # Env vars (passwords, ports, JVM memory, etc.)
├── copy.sh # Copy jar / SQL / frontend dist into deploy dir
├── bytech-cloud/ # Build contexts per service (Dockerfile + jar)
│ ├── gateway/ auth/ platform/ system/ file/ ai/ job/ monitor/ boot/
├── mysql/ redis/ nacos/ # Middleware configs & init scripts
└── nginx/ # Frontend static assets + reverse proxy (microservices)
```
### Deploy Steps
```bash
# 1. Package all modules from project root
mvn clean package -DskipTests
# 2. Enter docker dir and copy artifacts
cd docker-bytech
cp .env.example .env # edit passwords and other vars
./copy.sh # copy jar / SQL / frontend dist
# 3. Build images
docker compose build
# 4. Start (choose one)
docker compose --profile monolith up -d # monolith mode
docker compose --profile microservices up -d # microservice mode
```
### Mode Comparison
| Mode | Profile | Services | Depends On | Entry Point |
|------|---------|----------|------------|-------------|
| **Monolith** | `monolith` | `bytech-boot` + MySQL + Redis | No Nacos | `http://localhost:${BOOT_PORT:-8080}` |
| **Microservice** | `microservices` | gateway/auth/system/platform/file/ai/job/monitor + xxl-job-admin + Nacos + MySQL + Redis + Nginx | Nacos required | `http://localhost:${NGINX_PORT:-80}` |
- **Monolith**: `bytech-boot` aggregates all modules, connects directly to MySQL + Redis, no Nacos / Feign, zero network overhead.
- **Microservice**: Services register via Nacos, unified entry via Gateway, frontend served through Nginx reverse proxy.
### Key Config (`.env`)
| Variable | Description | Default |
|----------|-------------|---------|
| `MYSQL_ROOT_PASSWORD` | MySQL root password | - |
| `REDIS_PASSWORD` | Redis password (`requirepass` in container) | - |
| `NACOS_AUTH_ENABLE` | Nacos auth switch (microservice mode) | `false` |
| `MYSQL_HOST` / `REDIS_HOST` | Container service names, `mysql` / `redis` | `mysql` / `redis` |
| `JAVA_XMS` / `JAVA_XMX` | Microservice JVM memory (default mid-tier) | `256m` / `512m` |
| `BOOT_JAVA_XMS` / `BOOT_JAVA_XMX` | Monolith JVM memory (aggregates all modules, give more) | `512m` / `1024m` |
| `GATEWAY_PORT` / `BOOT_PORT` / `AUTH_PORT` / `TENANT_PORT` / `SYSTEM_PORT` / `FILE_PORT` / `AI_PORT` / `JOB_PORT` / `MONITOR_PORT` / `NGINX_PORT` | Host port mappings | `8080` / `8080` / `9001` / `9011` / `9021` / `9031` / `9042` / `9051` / `9041` / `81` |
> In monolith mode, env vars auto-bind to `application.yml` via `SPRING_REDIS_*` / `SA_TOKEN_ALONE_REDIS_*`, paired with the container service name `redis`, so no manual DB address changes are needed.
### Common Commands
```bash
docker compose --profile monolith logs -f bytech-boot # monolith logs
docker compose --profile microservices ps # microservice status
docker compose --profile monolith down # stop (keep volumes)
docker compose --profile monolith down -v # stop and remove data volumes
```
## Quick Start
### Prerequisites
- JDK 17+
- MySQL 8.0+
- Redis 7.x
- Nacos 2.x (microservice mode only)
- Maven 3.8+
### 1. Initialize Database
```sql
CREATE DATABASE bytech_platform DEFAULT CHARACTER SET utf8mb4;
CREATE DATABASE bytech_system DEFAULT CHARACTER SET utf8mb4;
source sql/bytech_platform.sql;
source sql/bytech_system.sql;
```
### 2. Monolith Mode (Quick Start)
```bash
mvn clean package -pl bytech-boot -DskipTests
java -jar bytech-boot/target/bytech-boot-exec.jar --spring.profiles.active=monolith
```
Open `http://localhost:8080`, default credentials `admin` / `admin123`.
### 3. Microservice Mode
3.1 Start Nacos + Redis + MySQL
3.2 Import Nacos configs from `nacos-configs/dev/`
3.3 Start services in order:
```bash
mvn spring-boot:run -pl bytech-gateway -Dspring.profiles.active=dev
mvn spring-boot:run -pl bytech-auth -Dspring.profiles.active=dev
mvn spring-boot:run -pl bytech-modules/bytech-system -Dspring.profiles.active=dev
mvn spring-boot:run -pl bytech-modules/bytech-platform -Dspring.profiles.active=dev
mvn spring-boot:run -pl bytech-modules/bytech-file -Dspring.profiles.active=dev
# AI (intelligent chat: multi-channel routing / channel management / conversation history)
mvn spring-boot:run -pl bytech-modules/bytech-ai -Dspring.profiles.active=dev
# Job (scheduled tasks: XXL-JOB distributed scheduling / task management / execution logs)
mvn spring-boot:run -pl bytech-modules/bytech-job -Dspring.profiles.active=dev
# Monitor (optional, system monitoring: service monitor / Redis monitor / online users)
mvn spring-boot:run -pl bytech-monitor -Dspring.profiles.active=dev
```
## Documentation
| Document | Description |
|----------|-------------|
| [Dual-Login Mechanism](docs/双系统同时登录机制.md) | Dual Token + currentLoginType switching (Chinese) |
| [Multi-Tenant Design](docs/multi-tenant-design.md) | Schema-level isolation design (Chinese) |
| [API Convention](docs/API_CALLING_CONVENTION.md) | Controller implements FeignClient dual-mode pattern (Chinese) |
| [RBAC Model](docs/RBAC数据库设计与逻辑说明.md) | Platform + Tenant RBAC design (Chinese) |
| [Frontend Login Logic](docs/前端登录两种系统类型逻辑分析.md) | Frontend dual-login state management (Chinese) |
| [Login Logic](docs/login-logic.md) | Auth flow details (Chinese) |
| [Database Spec](docs/database-specification.md) | Naming and design conventions (Chinese) |
| [System Config](docs/sys_config_design.md) | Parameter configuration module (Chinese) |
| [System Monitoring](docs/system-monitoring.md) | Service monitor / Redis monitor / online users (Chinese) |
| [AI Module](docs/ai-module.md) | Multi-channel routing chat / channel management / conversation history (Chinese) |
| [Scheduled Tasks Module](docs/job-module.md) | XXL-JOB distributed scheduling / task management / execution logs / dual-mode (Chinese) |
| [Login Captcha Design](docs/captcha-design.md) | Unified pluggable Image / SMS / TOTP captcha architecture and implementation (Chinese) |
| [WAF Design](docs/waf-design.md) | In-app WAF: dual-mode architecture, rule groups, canary rollout, four-level switches, lightweight observation, phased roadmap (Chinese) |
## License
MIT