Bu sayfa henüz yerel dilinizde mevcut değildir. Daha fazla dil seçeneği eklemek için yoğun bir şekilde çalışıyoruz. Desteğiniz için teşekkür ederiz.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Java Demo Usage Instruction

Updated on 2023-04-23 GMT+08:00

In addition to the native Kafka client described in the preceding sections, MQS (Kafka) instances can also be accessed in HTTP RESTful mode, including sending messages to specified topics, consuming messages, and acknowledging message consumption.

This mode is used to adapt to the original service system architecture and facilitate unified access using the HTTP protocol.

Using the RESTful Mode

  1. Collect connection information.

    The connection information includes the MQS connection address and port, topic name, and SASL username and password. For details, see Collecting Connection Information.

    NOTE:
    • If both SASL_SSL and intra-VPC plaintext access are enabled for MQS of the ROMA Connect instance, the SASL mode cannot be used for connecting to MQS topics in the VPC.
    • If the SASL mode is used for connecting to MQS topics, you are advised to configure the mapping between the host and IP address in the /etc/hosts file on the host where the client is located. Otherwise, network delay will occur.

      Set the IP address to the connection address of MQS and set the host to the name of each instance host. Ensure that the name of each host is unique. For example:

      10.10.10.11 host01

      10.10.10.12 host02

      10.10.10.13 host03

  2. Assemble an API request, including the signature of the API request, by referring to the sample code.

    API request signature: The SASL username and password are used as a key pair to sign the request URL and message header timestamp for backend service verification.

  3. For details about the structure of response messages returned when a demo project is used to create, retrieve, and confirm messages in a specified topic, see Message Production API, Message Consumption API, and Message Retrieval Confirmation API.

Sample Project Setup

This section provides an example of sending RESTful API requests in Java.

The following is a Maven project developed in IntelliJ IDEA. If you want to use the project in the local environment, install and configure the following environments (Windows 10 is used as an example):

  • Maven

    Apache Maven 3.0.3 or later can be downloaded from the Maven official website.

  • JDK

    Java Development Kit1.8.111 or later can be downloaded from the Oracle official website.

    After the installation, configure Java environment variables.

  • IntelliJ IDEA tool

    IntelliJ IDEA 2018.3.5 or later can be downloaded from the IntelliJ IDEA official website.

  • Demo

    On the ROMA Connect console, choose Message Queue Service > Topic Management. In the upper right corner of the page, choose User Guide > Download RESTful API Java Demo Package to download the demo.

  1. Start IntelliJ IDEA and choose Import Project.

    The Select File or Directory to Import dialog box is displayed.

  2. Select the directory where the RESTful API Java demo is decompressed and click OK.

  3. Select Eclipse for Import project from external model and click Next. Retain the default settings and click Next until the Please select project SDK page is displayed.

    Figure 1 Import Project dialog box

  4. Click Finish.

    Figure 2 Finish

  5. Edit the rest-config.properties file.

    The file is located in the src/main/resources directory. Enter the obtained Kafka instance connection address, topic name, and SASL information in the following configuration. kafka.rest.group indicates the consumer group ID, which can be specified on the client.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    # Kafka rest endpoint.
    kafka.rest.endpoint=https://{MQS_Instance_IP_Addr}:9292
    # Kafka topic name.
    kafka.rest.topic=topic_name_demo
    # Kafka consume group.
    kafka.rest.group=group_id_demo
    # Kafka sasl username.
    kafka.rest.username=sasl_username_demo
    # Kafka sasl password.
    kafka.rest.password=sasl_user_passwd_demo 
    

  6. Edit log4j.properties.

    For example, modify the directory for storing logs.

    1
    log.directory=D://workspace/logs
    

  7. Run the sample project to view the message production and consumption examples.

    The main method for producing and consuming messages is in the RestMain.java file. You can run the main method in Java Application mode.

Code of the Sample Project

  • Project entry

    The project entry is in the RestMain.java file.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    public class RestMain
    {
        private static final Logger LOGGER = LoggerFactory.getLogger(RestMain.class);
    
        public static void main(String[] args) throws InterruptedException
        {
            //Initialize the request object. The RestServiceImpl class file also contains the RESTful APIs and request signature.
            IRestService restService = new RestServiceImpl();
            Base64.Decoder decoder = Base64.getDecoder();
            //The following are message production, message consumption, and consumption confirmation.
            // Produce message
            ProduceReq messages = new ProduceReq();
            messages.addMessage("{[{'id': '00001', 'name': 'John'}, {'id': '00002', 'name': 'Mike'}]}").addMessage("Kafka rest client demo!");
            LOGGER.debug("produce message: {}", JsonUtils.convertObject2Str(messages));
            restService.produce(messages);
    
            // Consume message
            List<ConsumeResp> consumeResps = restService.consume();
            CommitReq commitReq = new CommitReq();
            consumeResps.forEach(resp ->
            {
                LOGGER.debug("handler: {}, content: {}", resp.getHandler(), new String(decoder.decode(resp.getMessage().getContent())));
                commitReq.addCommit(resp.getHandler());
            });
    
            // Commit message
            if (commitReq.getMessages().size() != 0)
            {
                CommitResp resp = restService.commit(commitReq);
                LOGGER.info("Commit resp: success: {}, failed: {}", resp.getSuccess(), resp.getFail());
            }
            else
            {
                LOGGER.warn("Commit is empty.");
            }
        }
    }
    
  • Message assembling and sending

    The following uses message production as an example to describe how to assemble and sign a message. After the signature method is invoked, two message headers are returned: Authorization and X-Sdk-Date. Authorization contains signature information of the requested content. Another parameter Content-Type in the message header must be added to the code. For details, see the createRequest() method in the example.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
     public List<ProduceResp> produce(ProduceReq messages)
        {
            List<ProduceResp> prodResp = null;
            try
            {
                Request request = createRequest();
                request.setUrl(produceURI);
                request.setMethod("POST");
                request.setBody(JsonUtils.convertObject2Str(messages));
                //After the request content is signed, two parameters are added to the request header: Authorization and X-Sdk-Date. Authorization contains signature information of the requested content.
                HttpRequestBase signedRequest = Client.sign(request);
                LOGGER.debug("Request uri: {}, headers: {}", signedRequest.getURI(), signedRequest.getAllHeaders());
                LOGGER.debug("Request body: {}", request.getBody());
    
                HttpResponse response = HttpUtils.execute(signedRequest);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)
                {
                    String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                    prodResp = JsonUtils.convertStr2ListObject(jsonStr, new TypeReference<List<ProduceResp>>() { });
                    LOGGER.info("Produce response: {}", jsonStr);
                    return prodResp;
                }
                else
                {
                    LOGGER.error("Produce message failed. statusCode: {}, error msg: {}",
                            response.getStatusLine().getStatusCode(),
                            EntityUtils.toString(response.getEntity(), "UTF-8"));
                }
            }
            catch (Exception e)
            {
                LOGGER.error("Produce message failed.");
            }
            return prodResp;
        }
    

Sitemizi ve deneyiminizi iyileştirmek için çerezleri kullanırız. Sitemizde tarama yapmaya devam ederek çerez politikamızı kabul etmiş olursunuz. Daha fazla bilgi edinin

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback