×
Community Blog ROS CDK Guide: Build Your Game World (Java)

ROS CDK Guide: Build Your Game World (Java)

This article describes how to use the Cloud Development Kit provided by Alibaba Cloud ROS to deploy 2048 games to the cloud.

This article describes how to use the Cloud Development Kit (CDK) provided by Alibaba Cloud Resource Orchestration Service (ROS) to deploy 2048 games to the cloud. ROS CDK allows you to define and deploy cloud resources through programming languages, simplifying the development process. Elastic Compute Service (ECS) provides flexible computing resources to ensure the stable running of applications. By following steps including initializing the project, installing dependencies, and adding resources, you can deploy your game on the cloud. The operation methods and precautions of each step are described in detail to help you deploy smoothly. Finally, you can delete the stack with a simple command for efficient resource management.

1. Introduction

In the world of virtual games, digitalization composes the shared memories of numerous players. In this world full of creativity and adventure, your goal is to combine a unique gaming experience with various technical knowledge to create something unforgettable. To realize this goal, you may wonder how to deploy a simple and interesting game to the cloud so that more players can share the fun.

Don't worry. You now have a tool, that is, the Cloud Development Kit (CDK) provided by Alibaba Cloud Resource Orchestration Service (ROS). With this powerful tool, you can easily create and manage cloud resources and securely and quickly deploy your 2048 games to the cloud.

In the following article, we will guide you through the process of deploying the 2048 game to an Alibaba Cloud instance using ROS CDK, providing a solid cloud foundation for your game. To help you avoid complicated configurations and tedious operations, we will guide you through the simplest steps to deploy your game, achieving a seamless migration from local to cloud.

2. Background

2.1 What is ROS CDK?

Imagine you are a game designer with a brand-new game world to build. In the traditional development process, you may need to build each element step by step and repeatedly test and optimize them, which is time-consuming and laborious and needs to handle a large number of technical details. However, with the Alibaba Cloud ROS CDK, you can easily generate the entire architecture of your game through a short piece of code.

ROS CDK is a powerful development framework that allows you to define, build, and deploy cloud resources with familiar programming languages. ROS CDK allows you to convert infrastructure into code (Infrastructure as Code, IaC) and create and configure cloud resources as easily as writing game logic.

This framework helps you write intuitive code that describes the overall structure of the game instead of configuring each component individually. These codes are then converted to specific cloud resource configurations, such as Elastic Compute Service (ECS), Object Storage Service (OSS), and database services, and quickly deployed on the cloud. This streamlined process makes the entire development process more efficient and repeatable, helping developers easily collaborate and share resources across teams.

Infrastructure as code reduces the risk of human error and makes cloud service management as easy as playing games. ROS CDK provides great convenience for the rapid development, upgrading, and scaling of game applications so that you can devote more energy to creativity and design rather than being plagued by tedious operations. In short, ROS CDK gives you endless possibilities to build the game world on the cloud, allowing your creativity to be realized in this digital world.

2.2 What is ECS?

In the vast domain of cloud computing, you are a developer in pursuit of knowledge and capability, eager to create a multitude of diverse applications and services. On this journey, you need a powerful supporter to provide continuous computing resources for your projects, that is, ECS.

ECS has numerous flexible and scalable instances, each of which provides powerful computing capabilities and can be combined to meet any of your needs. Whether for lightweight applications or complex computing tasks, ECS can respond quickly.

Deploying your applications on ECS is like setting up a permanent and reliable hosting environment for them. No matter what happens, ECS provides you with highly reliable computing power to ensure that every idea can be turned into reality in an instant, supporting the continuous development of your applications.

Like an assistant, ECS guides you to flexibly deploy and manage computing resources. Its intelligent monitoring and auto-scaling capabilities enable you to fully control the flow of demand without worrying about the shortage and waste of resources. Robust security features, such as network isolation and access control, protect your applications from external intrusion, ensuring that your development and creative work can thrive in a secure environment.

In Alibaba Cloud, ECS has become the best partner for every developer to realize their creative visions and explore endless possibilities. No matter how grand your dreams or how challenging the tasks are, ECS will always be a reliable platform where you can fully unleash your wisdom and creativity on the cloud. Therefore, as you prepare to plan your future on the cloud, ECS will be an indispensable tool, helping you to achieve greater success.

3. Preparations

3.1 Language Requirements

Before entering the IaC world, we still need some preparations. To install ROS CDK, Node.js, TypeScript, and Java of the following versions are used:

Node.js: 14.17.0 or later

TypeScript: 3.8 or later

Java: Java Development Kit (JDK) and Maven of the following versions are used:

JDK: 8 or later

Maven: 3.6 or later

3.2 Initialize the Project

First, install ROS CDK.

Note: Please make sure that the version of ros-cdk-cli you install is 1.0.50 or later. You can confirm it by running npm list -g.

In your practice, whenever you plan to start a new project, you need to make some preparations in your programming environment. You need to ensure you have a project framework, configurations, and access credentials for the cloud platform.

Initializing the project is like laying out a blueprint in your programming environment with the basic outline of the project to be completed. On your computer, this means creating a new directory containing the necessary file structure, giving the developers a place to code.

Configuring credential information is to obtain an AccessKey, which grants you the authority to control resources and manage data on the cloud. In the Alibaba Cloud world, this means that you need to configure the AccessKey ID and Secret AccessKey for authentication in the local environment. In this way, when you use ROS CDK, it ensures that you are an authorized developer with the rights to manage these cloud resources, rather than an unintentional intruder.

Before we proceed with more advanced tasks, let's first set up the environment.

1.  Run the following command to create a project directory and initialize the project:

mkdir demo
cd demo
ros-cdk init --language=java --generate-only=true

2.  Run the following command to configure an Alibaba Cloud credential:

ros-cdk config

3.  Set the credential parameters:

endpoint(optional, default:https://ros.aliyuncs.com):
defaultRegionId(optional, default:cn-hangzhou):

[1] AK
[2] StsToken
[3] RamRoleArn
[4] EcsRamRole
[0] CANCEL

Authenticate mode [1...4 / 0]: 1
accessKeyId:************************
accessKeySecret:******************************

Parameter description:

endpoint: the endpoint of ROS. Default value: https://ros.aliyuncs.com

defaultRegionId: the ID of the region where you want to deploy the ROS stack. Default value: cn-hangzhou.

Authenticate mode: the authentication method. In this example, an AccessKey pair is used for authentication. In this case, you must specify the AccessKey ID and the AccessKey Secret. For more information about how to obtain an AccessKey pair, see Configure a credential in interactive mode (fast).

With everything ready, let us begin our journey with ROS CDK.

4. Best Practice: Deploy 2048 Games in the Cloud

In this part, we will use a best practice case to demonstrate how to deploy 2048 games on a cloud server.

Before performing the following steps, make sure that you have completed all necessary preparations, including environment configuration and project initialization.

4.1 Install Dependencies

First, we need to install the dependencies required for developing the CDK project.

Enter the project initialized in the Preparations step and modify the contents of the pom.xml file as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
         xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myorg</groupId>
    <artifactId>demo</artifactId>
    <version>0.1</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <cdk.version>1.1.0</cdk.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.6.0</version>
                <configuration>
                    <mainClass>com.myorg.DemoApp</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- AliCloud ROS Cloud Development Kit (ROS CDK) -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>ros-cdk-core</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>ros-cdk-ecs</artifactId>
            <version>1.1.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

After the modification is complete, run the following command to install dependencies:

mvn compile

4.2 Add Resources

In this part, we will add resources to the project. The resources involved in this example include:

ALIYUN::ECS::SecurityGroup

ALIYUN::ECS::SecurityGroupIngress

ALIYUN::ECS::Instance

ALIYUN::ECS::VPC

ALIYUN::ECS::VSwitch

ALIYUN::ECS::RunCommand

The billable items involved in this project include:

ECS: pay-as-you-go

Go to the project directory and modify the contents of src/main/java/com/myorg/DemoStack.java as follows:

package com.myorg;

import com.aliyun.ros.cdk.core.*;
import com.aliyun.ros.cdk.ecs.*;

import java.util.ArrayList;
import java.util.Arrays;

public class DemoStack extends Stack {
    public DemoStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public DemoStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // The code that defines your stack goes here
        RosInfo.setDescription("Deploy 2048 game through ROS CDK.");
        RosParameter zoneId = RosParameter.Builder.create(this, "ZoneId")
                .type(RosParameterType.STRING)
                .build();

        Vpc vpc = Vpc.Builder.create(this, "Vpc")
                .cidrBlock("192.168.0.0/16")
                .build();

        SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup")
                .vpcId(vpc.getRef())
                .build();

        VSwitch vSwitch = VSwitch.Builder.create(this, "VSwitch")
                .cidrBlock("192.168.0.0/24")
                .zoneId(zoneId.getValue())
                .vpcId(vpc.getRef())
                .build();

        Instance instance = Instance.Builder.create(this, "Instance")
                .vpcId(vpc.getRef())
                .vSwitchId(vSwitch.getRef())
                .securityGroupId(securityGroup.getRef())
                .zoneId(zoneId.getValue())
                .instanceType("ecs.c6e.large")
                .imageId("centos_7_8")
                .systemDiskCategory("cloud_essd")
                .ioOptimized("optimized")
                .build();

        SecurityGroupIngress securityGroupIngress = SecurityGroupIngress.Builder.create(this, "SecurityGroupIngress")
                .ipProtocol("tcp")
                .portRange("80/80")
                .sourceCidrIp("0.0.0.0/0")
                .securityGroupId(securityGroup.getRef())
                .nicType("intranet")
                .build();

        RunCommand runCommand = RunCommand.Builder.create(this, "RunCommand")
                .instanceIds(new ArrayList<>(Arrays.asList(instance.getRef())))
                .type("RunShellScript")
                .sync(true)
                .timeout(3600)
                .commandContent("yum install -y httpd wget\nsystemctl start httpd\nwget 'https://computenest-artifacts-cn-hangzhou.oss-cn-hangzhou-internal.aliyuncs.com/1853370294850618/cn-beijing/1697533575326/2048.tgz' -O 2048.tgz\ntar xvf 2048.tgz\nmv 2048/* /var/www/html && rm -rf 2048")
                .build();
        runCommand.addDependency(securityGroupIngress);

        RosOutput.Builder.create(this, "Url")
                .value("http://" + instance.getAttrPublicIp().toString() +":80")
                .build();
    }
}

Run mvn compile to compile the CDK project.

4.3 Deploy the Stack

Run the following command to deploy the stack:

ros-cdk deploy --parameters ZoneId=cn-hangzhou-i --sync=true

--sync=true synchronizes the stack information and displays it in the terminal. Upon success, the command-line terminal returns the following information:

Create bucket(cdk-tcbgaxxxx-assets-cn-hangzhou) successfully!
Upload file(./cdk.out/DemoStack.template.json) to bucket(cdk-tcbgaxxxx-assets-cn-hangzhou) successfully!
DemoStack: deploying...
|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroup | sg-bp121z2wd687mdxxxxxx | SecurityGroup

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroupIngress | sg-bp121z2wd687mdxxxxxx | SecurityGroupIngress

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::Instance   | i-bp16t9mt9b0uscixxxxx | Instance

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::VPC        | vpc-bp10y18ke2x6v0bjxxxxx | Vpc

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::VSwitch    | vsw-bp1qfb9u90cuyu69xxxxx | VSwitch

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::RunCommand | t-hz04w6ckiuxxxxx | RunCommand


Outputs:

 Key: Url  Value: http://121.40.xxx.xx:80 Description: No description given

 ✅ The deployment(sync create stack) has completed!
Status: CREATE_COMPLETE
StatusReason: Stack CREATE completed successfully
StackId: 40c92773-33fb-4249-bd46-3ab6xxxxxxxx

After the deployment is complete, copy the link in Outputs and open it in your browser to play 2048!

1

4.4 Delete the Stack

Run the following command to delete the stack:

ros-cdk destroy --sync=true 

CDK reconfirms the stack to be deleted:

The following stack(s) will be destroyed(Only deployed stacks will be displayed).

DemoStack

Please confirm.(Y/N)

Enter y and press the Enter key. After deletion, the following information is displayed:

✅ The task(sync destroy stack) has finished!
status: DELETE_COMPLETE
StatusReason: Stack DELETE completed successfully
StackId: 40c92773-33fb-4249-bd46-3ab6xxxxxxxx

Disclaimer: The views expressed herein are for reference only and don't necessarily represent the official views of Alibaba Cloud.

0 0 0
Share on

Alibaba Cloud Community

1,075 posts | 263 followers

You may also like

Comments

Alibaba Cloud Community

1,075 posts | 263 followers

Related Products