All Products
Search
Document Center

Enterprise Distributed Application Service:Use the EDAS SDK to develop HSF applications

Last Updated:Aug 17, 2023

This topic describes how to use the Enterprise Distributed Application Service (EDAS) SDK to accelerate the development of High-Speed Service Framework (HSF) applications and implement service registration and discovery.

Prerequisites

Before you develop an application, make sure that the following operations are complete:

Download a demo project

You can perform the steps that are described in this topic to build a project, directly download the sample project, or download the sample project by running git clone https://github.com/aliyun/alibabacloud-microservice-demo.git.

This project contains a number of sample projects. The sample project of this topic is in alibabacloud-microservice-demo/microservice-doc-demo/hsf-ali-tomcat, including the itemcenter-api, itemcenter, and detail Maven project directories.

  • itemcenter-api: provides the API definition.
  • itemcenter: contains the sample code of the service provider.
  • detail: contains the sample code of the service consumer.
Note Use Java Development Kit (JDK) 1.7 or later.

Define the service API

The HSF service framework enables service communication over the API. When the API is defined, providers implement and publish specific services by using this API, and consumers also subscribe to and consume services by using this API.

In the itemcenter-api project of the demo, define the com.alibaba.edas.carshop.itemcenter.ItemService API.
public interface ItemService {
    public Item getItemById(long id);
    public Item getItemByName(String name);
}

The API provides the getItemById and getItemByName methods.

Develop a service provider

A service provider implements the service API to provide a specific service. If the Spring framework is used, the service provider also needs to configure service properties in the XML file.
Note In the Demo project, the itemcenter directory contains the sample code of the service provider.
  1. Implement the service API.
    Construct the service API based on sample code in the ItemServiceImpl.java file.
    public class ItemServiceImpl implements ItemService {
    
        @Override
        public Item getItemById( long id ) {
            Item car = new Item();
            car.setItemId( 1l );
            car.setItemName( "Mercedes Benz" );
            return car;
        }
        @Override
        public Item getItemByName( String name ) {
            Item car = new Item();
            car.setItemId( 1l );
            car.setItemName( "Mercedes Benz" );
            return car;
        }
    }
  2. Configure the service provider.

    The com.alibaba.edas.carshop.itemcenter.ItemService service API is implemented in Implement the service API, and the Item object is returned in both methods. After code development is complete, configure the required settings and add Maven dependencies in the web.xml file, and use the <hsf /> tag to register and publish the service in the Spring profile.

    1. Add the Maven dependencies to the pom.xml file.
        <dependencies>
            <!-- Add the Servlet dependency. -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
                <scope>provided</scope>
            </dependency>
            <!-- Add the service API dependency. -->      
            <dependency>
                <groupId>com.alibaba.edas.carshop</groupId>
                <artifactId>itemcenter-api</artifactId>
                <version>1.0.0-SNAPSHOT</version>
            </dependency>
            <!-- Add the Spring dependency. -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>2.5.6 (and later)</version>
            </dependency>
            <!-- Add the edas-sdk dependency. -->
            <dependency>
                  <groupId>com.alibaba.edas</groupId>
                   <artifactId>edas-sdk</artifactId>
                  <version>1.8.1</version>
            </dependency>
        </dependencies>
    2. Add Spring configurations for the HSF service to the hsf-provider-beans.xml file.
        <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:hsf="http://www.taobao.com/hsf"
            xmlns="http://www.springframework.org/schema/beans"
            xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.taobao.com/hsf
            http://www.taobao.com/hsf/hsf.xsd" default-autowire="byName">
            <!-- Define the implementation of the service. -->
            <bean id="itemService" class="com.alibaba.edas.carshop.itemcenter.ItemServiceImpl" />
            <!-- Use the hsf:provider tag to define a service provider. -->
            <hsf:provider id="itemServiceProvider"
                <!-- Use the interface property to indicate that the service is an implementation of the interface class. -->
                interface="com.alibaba.edas.carshop.itemcenter.ItemService"
                <!-- The Spring object that is implemented by the service. -->
                ref="itemService"
                <!-- The version number of the published service. The version number is user-defined and the default value is 1.0.0. -->
                version="1.0.0"
            </hsf:provider>
        </beans>

      The preceding example shows the basic configurations. You can add other properties based on your business requirements. For more information about the properties, see the service provider properties that are described in the following table.

      PropertyDescription
      interfaceRequired. The API for providing services. The data type is STRING.
      versionOptional. The version of the service. The default value is 1.0.0. The data type is STRING.
      clientTimeoutThis property applies to all methods in the API. However, if the consumer specifies a timeout period for a method by using the methodSpecials property, the specified timeout period takes precedence over this property value for this method. Other methods still use the time-out period that is configured on the provider.
      serializeTypeOptional. The serialization type. The default type is hessian. The data type is String(hessian|java).
      corePoolSizeThe size of the core thread pool that is allocated from the public thread pool for this service.
      maxPoolSizeThe maximum size of the thread pool that is allocated from the public thread pool for this service.
      enableTXCThis property enables the distributed transaction middleware GTS.
      refRequired. The ID of the Spring bean that you want to publish as an HSF service. The data type is ref.
      methodSpecialsOptional. The time-out period (unit: millisecond) for a single method. This way, different time-out periods can be specified for different methods in the API. This time-out property takes precedence over clientTimeout but defers to methodSpecials on the consumer.

      The following table describes the limits on service creation and publishing.

      ParameterExampleMaximum sizeAdjustable
      {Service name}:{Version number}com.alibaba.edas.testcase.api.TestCase:1.0.0 192 bytesNo
      Group nameHSF 32 bytesNo
      Number of services published by a single Pandora application instanceN/A 800Yes. On the Basic Information tab, you can click Setting on the right of Application Settings and select JVM from the drop-down list. In the Application Settings dialog box, choose Custom > Custom Parameters and enter -DCC.pubCountMax=1200 in the field. You can change the value of the Custom Parameters parameter based on the number of published services.
      Sample configuration of service provider properties:
      <bean id="impl" class="com.taobao.edas.service.impl.SimpleServiceImpl" />
      <hsf:provider
              id="simpleService"
              interface="com.taobao.edas.service.SimpleService"
              ref="impl"
              version="1.0.1"
              clientTimeout="3000"
              enableTXC="true"
              serializeType="hessian">
              <hsf:methodSpecials>
                  <hsf:methodSpecial name="sum" timeout="2000" />
              </hsf:methodSpecials>
      </hsf:provider>

Develop a service consumer

Service subscription for consumers is coded in two steps:
  • Use the <hsf:consumer/> tag in the Spring profile to define a bean.
  • Retrieve the bean from the Spring context to locate the service.
Note The detail directory in the demo project contains sample code of service consumers.
Service property configuration for a consumer consists of the Maven dependency configuration and Spring configuration. The service property configuration for the consumer is similar to that for a provider.
  1. Configure the service properties.
    1. Add the Maven dependencies to the pom.xml file.
      <dependencies>
            <!-- Add dependencies of servlet -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
                <scope>provided</scope>
            </dependency>
            <!-- Add dependencies of Spring -->
            <dependency>
                <groupId>com.alibaba.edas.carshop</groupId>
                <artifactId>itemcenter-api</artifactId>
                <version>1.0.0-SNAPSHOT</version>
            </dependency>
            <!-- dd dependencies of Service interface -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>2.5.6(And above)</version>
            </dependency>
            <!-- Add dependencies of edas-sdk -->
            <dependency>
                  <groupId>com.alibaba.edas</groupId>
                   <artifactId>edas-sdk</artifactId>
                  <version>1.8.1</version>
            </dependency>
        </dependencies>
    2. Add Spring configurations for the HSF service to the hsf-consumer-beans.xml file.
      Add the consumer definition in the Spring configuration file. Then, the HSF framework subscribes to the specified services from the service registry by using the configuration file.
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns:hsf="http://www.taobao.com/hsf"
              xmlns="http://www.springframework.org/schema/beans"
              xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
              http://www.taobao.com/hsf
              http://www.taobao.com/hsf/hsf.xsd" default-autowire="byName">
              <! -- The example of consuming a service. -->
              <hsf:consumer
                  <!-- The bean ID that is used to retrieve the consumer object by code injection.  -->
                  id="item"
                  <!-- The name of the service. It corresponds to the service name of the service provider. The HSF consumer queries and subscribes to services based on the values of the interface and version parameters.  -->
                  interface="com.alibaba.edas.carshop.itemcenter.ItemService"
                  <!-- The version number that corresponds to the version number of the service provider. The HSF consumer queries and subscribes to services based on the values of the interface and version parameters.  -->
                  version="1.0.0">
              </hsf:consumer>
      </beans>
  2. Configure the service consumer.
    For more information, see the example in the StartListener.java file.
    public class StartListener implements ServletContextListener{
    
        @Override
        public void contextInitialized( ServletContextEvent sce ) {
            ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext( sce.getServletContext() );
            // Retrieve subscribed services based on the bean ID "item" in the Spring configuration.
              final ItemService itemService = ( ItemService ) ctx.getBean( "item" );
            ……
            // Call the getItemById method of ItemService.
               System.out.println( itemService.getItemById( 1111 ) );
            // Call the getItemByName method of ItemService.
               System.out.println( itemService.getItemByName( "myname is le" ) );
            ……
        }
    }

    The preceding example shows the basic configurations. You can add other properties based on your business requirements. For more information about the properties, see the service properties that are described in the following table.

    PropertyDescription
    interfaceRequired. The API of the service to be called. The data type is STRING.
    versionOptional. The version of the service to be called. The default value is 1.0.0. The data type is STRING.
    methodSpecialsOptional. The time-out period for a single method. Unit: millisecond. Different time-out periods can be specified for different methods in the API. This time-out property takes precedence over that of the service provider.
    targetThis property is used in the unit test environment and development environment to manually specify the address of the service provider. If you need to specify the provider address based on the required service address that is pushed by the configuration center, you can set -Dhsf.run.mode to 0 on the consumer.
    connectionNumOptional. The maximum number of connections to the server. Default value: 1. If you need to transmit a small amount of data at a shorter latency, set this property to a larger value to improve transactions per second (TPS).
    clientTimeoutThe time-out period specified by the consumer for all the methods in the API. Unit: millisecond. Time-out settings are sorted in the following descending order of priority: consumer methodSpecials, consumer API level, provider methodSpecials, and provider API level.
    asyncallMethodsOptional. The list of methods for asynchronous calls on the service. The default value is null. It indicates that all the methods are used for synchronous calls.
    maxWaitTimeForCsAddressThe time during which the thread is blocked to wait for address push when a service is subscribed. Otherwise, the address cannot be found due to an empty address when the service is called. If the address is not pushed within the blocking time, the thread does not wait and proceeds with initialization. Take note of the following item: This parameter is used to call only a service when the application is initialized. We recommend that you do not use this parameter when no other services need to be called. This is because this parameter extends the startup time.
    Sample configuration of service consumer properties:
    <hsf:consumer
          id="service"
          interface="com.taobao.edas.service.SimpleService"
          version="1.1.0"
          clientTimeout="3000"
          target="10.1.6.57:12200?_TIMEOUT=1000"
          maxWaitTimeForCsAddress="5000">
          <hsf:methodSpecials>
               <hsf:methodSpecial name="sum" timeout="2000" ></hsf:methodSpecial>
          </hsf:methodSpecials>
    </hsf:consumer>

Run services in your on-premises environment

After code and API development and service configuration, you can run the service by using Ali-Tomcat in Eclipse or IntelliJ IDEA. For more information, see Install Ali-Tomcat and Pandora and configure development environments.

When you configure the development environment, you can add the following JVM startup properties to change the behavior of HSF.

PropertyDescription
-Dhsf.server.portThe port bound to the HSF startup service. Default value: 12200.
-Dhsf.serializerThe serialization method of HSF. Default value: Hessian.
-Dhsf.server.max.poolsizeThe maximum size of the thread pool of the HSF provider. Default value: 720.
-Dhsf.server.min.poolsizeThe minimum size of the thread pool of the HSF provider. Default value: 50.
-DHSF_SERVER_PUB_HOSTThe IP address for providing services over the Internet. If this property is not specified, the value of -Dhsf.server.ip is used.
-DHSF_SERVER_PUB_PORTThe port for providing services over the Internet. It must be listened to on the local host and be available for access. By default, the value of -Dhsf.server.port is used. If -Dhsf.server.port is not configured, 12200 is used by default.

Query HSF services in your on-premises environment

For example, your service is registered and discovered by using the light-weight configuration center. When you develop and debug an application, you can query the services that are provided or called by the application in the EDAS console.

In this example, you start the EDAS configuration center on an Elastic Compute Service (ECS) instance whose IP address is 192.168.XX.XX.
  • Access http://192.168.xx.xx:8080/.
  • In the left-side navigation pane, click Services. Specify the Service name, Grouping, or IP parameters to search for the service provider and caller.
    Note After the configuration center is started, the address of the first network interface card (NIC) is used as the service discovery address by default. If your ECS instance has multiple NICs, configure the SERVER_IP variable in the startup script to bind an address.

Common query cases

  • Providers tab
    • Enter the IP address in the search box and click the search icon to query the services that are provided by the host of the specified IP address.
    • In the search box, enter the service name or the service group name to search for the IP address of the host that provides the service.
  • Callers tab
    • Enter the IP address in the search box and click the search icon to query the services that are called by the host of the specified IP address.
    • In the search box, enter the service name or the service group name to search for the IP address of the host that calls the service.

Deploy applications to EDAS

On-premises applications that use the light-weight configuration center can be directly deployed to EDAS. The registry is automatically replaced with the EDAS registry without modifications.

To pack a WAR package that can run in EDAS Container, you must add the following Maven packaging plug-in.

  1. Add the following configuration of the packaging plug-in to the pom.xml file:
       <build>
           <finalName>itemcenter</finalName>
           <plugins>
               <plugin>
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-compiler-plugin</artifactId>
                   <version>3.1</version>
               </plugin>
           </plugins>
       </build>
  2. Run the mvn clean package command to package your on-premises program into a WAR package.

Select EDAS Container for the application runtime environment.

For more information about deployment operations, see Deploy applications to ECS clusters and Use an image to deploy a Java microservices application in a Kubernetes cluster.