jforgame Framework

repository·master·Indexed 22 days ago

https://github.com/kingston-csj/jforgame

A lightweight, high-performance Java framework for building mobile and web game servers. It supports Socket and WebSocket protocols, hot-swapping, and a custom ORM. Key components include jforgame-codec for message serialization (JsonCodec, ProtobufCodec, and StructCodec), jforgame-commons for event bus communication, asynchronous data persistence via PersistContainer, and TrieDictionary for sensitive word detection. The jforgame-data module provides configuration data management with support for CSV, Excel, and JSON files, featuring hot-reloading and Spring Boot integration.

Tokens
28.8K
Snippets
93
Records
126
Agent score
77%

What's inside jforgame

  1. Overview of jforgame

    master

    jforgame is a lightweight, high-performance Java-based server framework designed for mobile games. It provides various components to accelerate secondary development and tools for managing production environments.

    Key features include:

    • Support for Socket and WebSocket (compatible with mobile, web, and H5 games).
    • Multiple communication protocols: JSON, Protobuf, or standard JavaBeans.
    • One-click export of communication protocols to C# or TypeScript.
    • Built-in cross-process communication and powerful async/sync APIs for cross-server business.
    • Custom lightweight ORM supporting multiple data sources and automatic table/field updates.
    • Support for hot-swapping code and configurations without downtime.
  2. Overview of jforgame-orm

    master

    jforgame-orm

    jforgame-orm is a lightweight ORM framework specifically designed for the gaming domain. Unlike traditional ORMs, it prioritizes performance and responsiveness through several key architectural decisions:

    • Single-Table Operations: Each operation involves only one table, removing the need for complex transaction consistency.
    • Cache-First Approach: Data is written to an in-memory cache first to ensure high responsiveness.
    • Asynchronous Persistence: Data is periodically written to the database in batches to improve performance.
    • Eventual Consistency: Relies on external mechanisms to ensure data eventually reaches a consistent state.

    Key Features:

    • Lightweight API similar to Apache DbUtils.
    • Supports multiple data sources.
    • Supports both full-field and incremental field updates.
    • Supports JPA standard javax.persistence.AttributeConverter for property transformations.
    • Automatic database table creation and field addition (does not delete fields or change types).
    • Provides various asynchronous persistence containers.
  3. Understand the jforgame-threadmodel module

    master

    The jforgame-threadmodel module provides concurrency abstractions specifically for game servers, focusing on the Actor model and keyword-based thread dispatching.

    Key characteristics:

    • Agnostic to business logic: It does not understand sockets, sessions, or messages; it only manages Runnable tasks.
    • Concurrency focus: It handles task queuing, thread execution, shutdown strategies, and concurrency conflict avoidance.
    • Dispatching modes: Supports hash-based dispatching (via keywords) or Actor-based scheduling.
  4. Choose a MessageCodec implementation

    master

    Depending on your project's performance and complexity requirements, you can choose from three implementations of MessageCodec:

    1. JsonCodec: Best for lightweight games, small projects, or rapid prototyping. It is easy to debug and has excellent cross-language support but moderate performance.
    2. ProtobufCodec: Best for high-performance projects requiring small serialization size and multi-language support. Requires defining .proto files (can be generated via ProtobufIDLGenerator) and annotating message classes with @ProtobufClass.
    3. StructCodec: Best for extreme performance needs and high customization. It uses a binary format and supports polymorphism in collections. Requires message classes to have getters/setters and a no-args constructor.
  5. Implement asynchronous data persistence with PersistContainer

    master

    The persist module provides containers to manage how data is saved to a database via a DbService. You can choose from several strategies:

    • Queue Strategy (QueueContainer): Data is added to a queue and saved in batches periodically.
    • Delay Strategy (DelayContainer): Data is persisted after a specified delay following a change to avoid frequent writes.
    • Cron Strategy (CronContainer): Data is persisted according to a Cron expression.

    To use a container, implement the Entity interface on your objects and provide a DbService implementation.

    // Create a queue-based persistence container
    QueueContainer<Player> container = new QueueContainer<>(playerService, 1000);
    
    // Add an object to be persisted
    container.add(player);
    
    // Trigger the batch save
    container.save();
  6. How automatic framework detection works

    master

    The jforgame-logger module automatically detects which logging framework is present in your application's classpath via SLF4J bindings. It then selects the appropriate internal adapter to ensure compatibility without requiring manual configuration.

    Detected FrameworkImplementation Class
    LogbackLogbackAppLogger
    Log4j2Log4J2AppLogger
    Log4j (1.x)Log4JAppLogger
    Other SLF4JSlf4JAppLogger
  7. Manage entity states and lifecycle

    master

    Entities in jforgame-orm track their own database state to manage persistence operations. To use these features, all entities must extend BaseEntity.

    Entity States

    • NORMAL: Standard state; no persistence required.
    • UPDATE: Marked for update; needs to be synchronized with the database.
    • INSERT: New entity; needs to be inserted into the database.
    • DELETE: Marked for deletion; will be physically removed from the database.

    Lifecycle Hooks

    The framework uses specific hooks to manage these states automatically:

    • afterLoad(): Called after loading from the database; marks the entity as being in a persistent state.
    • beforeSave(): Called before persistence; automatically identifies if the entity is an INSERT or an UPDATE.
    • afterSave(): Called after persistence; resets the entity to the NORMAL state.
  8. How the Actor Model works in jforgame

    master

    The Actor model achieves concurrency control through message passing. Each Actor has its own mailbox, ensuring that tasks sent to a specific Actor are processed serially.

    Core Components:

    • ActorSystem: The container managing Actor instances.
    • BaseActor: The individual Actor instance.
    • Mailbox: The queue for incoming messages. Supported types include UnboundedMailbox, BoundedMailbox, and PriorityMailbox.
    • Mail (Message): The data sent to Actors. Supported types include SimpleMail and PriorityMail (for priority-based processing).
    ActorSystem (Actor System)
        ├── BaseActor (Actor Instance)
        │     └── Mailbox (Mailbox)
        │           ├── UnboundedMailbox (Unbounded Mailbox)
        │           ├── BoundedMailbox (Bounded Mailbox)
        │           └── PriorityMailbox (Priority Mailbox)
        ├── SharedActor (Shared Actor)
        └── Mail (Message)
              ├── SimpleMail (Simple Message)
              └── PriorityMail (Priority Message)
  9. Understand the ThreadModel abstraction

    master

    The ThreadModel is the top-level abstraction for thread scheduling in jforgame-threadmodel. It is designed to be agnostic of business semantics (like sockets or sessions) and focuses purely on concurrency concerns such as task queuing, thread execution, shutdown strategies, and avoiding concurrency conflicts. It accepts Runnable tasks and executes them according to the specific implementation's model.

    Core methods defined in the ThreadModel interface:

    • void accept(Runnable task): Receives a new task for execution.
    • void shutDown(): Shuts down the thread model.
    • boolean isShutdown(): Checks if the model has been shut down.
    public interface ThreadModel {
        void accept(Runnable task);
        void shutDown();
        boolean isShutdown();
    }
  10. Format CSV/Excel files for jforgame

    master

    Data files (CSV/Excel) must follow a specific structure for the parser to work correctly:

    1. Header/Metadata: Any rows above the HEADER line are ignored (useful for comments).
    2. HEADER Line: This line must contain the names of the fields. Parsing begins on the row immediately following this line.
    3. END Line: The parser stops reading once it encounters a row containing END. Data below this line is ignored.
    4. Export Control (Optional): A row containing EXPORT can be used to specify field visibility:
      • SERVER: Field is for the server only.
      • CLIENT: Field is for the client only.
      • BOTH: Field is for both.
      • Blank: Field is for designer notes only and is not exported.
  11. Understand how jforgame-logger automatically adapts to logging frameworks

    master

    The LoggerBuilder automatically detects the underlying SLF4J binding used in your application and selects the appropriate adapter. This allows the library to work without manual configuration regardless of whether you use Logback, Log4j2, or Log4j (1.x).

    Detected FrameworkImplementation Class
    LogbackLogbackAppLogger
    Log4j2Log4J2AppLogger
    Log4j (1.x)Log4JAppLogger
    Other SLF4JSlf4JAppLogger
  12. Data validation and integrity

    master

    The module provides mechanisms to ensure data integrity through two types of validators:

    1. ForeignKeyValidator: Automatically checks that foreign key references exist in their respective target tables.
    2. CustomValidator: Allows for manual validation logic by implementing custom checks and calling Container.validate().