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.

Download the demo project

You can follow the steps 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 many 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 interface definition.
  • itemcenter: contains sample code of the service provider.
  • detail: contains sample code of the service consumer.
Note Use JDK 1.7 or later.

Define the service interface

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

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

The interface provides the getItemById and getItemByName methods.

Develop a service provider

A service provider implements service interfaces to provide specific services. 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 sample code of the service provider.
  1. Implement the service interface.
    Construct the service interface according to 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 interface is implemented in Implement the service interface, and the Item object is returned in both methods. After code development, configure general items and add Maven dependencies in the web.xml file, and use the <hsf /> tag to register and publish the service in the Spring configuration file.

    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 Spring dependency. -->
            <dependency>
                <groupId>com.alibaba.edas.carshop</groupId>
                <artifactId>itemcenter-api</artifactId>
                <version>1.0.0-SNAPSHOT</version>
            </dependency>
            <! -- Add the service interface dependency. -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>2.5.6 (or 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 of the published service, which is user-defined and is 1.0.0 by default. -->
                version="1.0.0"
            </hsf:provider>
        </beans>

      The preceding example shows the basic configurations. You can add other properties as needed by referring to the service provider properties in the following table.

      Property Description
      interface Required. The interface for providing services. The data type is String.
      version Optional. The version of the service. The default value is 1.0.0. The data type is String.
      clientTimeout This property applies to all methods in the interface. However, if the consumer sets a timeout period for a method by using the methodSpecials property, the set timeout period takes precedence over this property value for this method. Other methods still use the timeout period configured on the provider.
      serializeType Optional. The serialization type. The default type is hessian. The data type is String(hessian|java).
      corePoolSize The size of the core thread pool that is allocated from the public thread pool for this service.
      maxPoolSize The maximum size of the thread pool that is allocated from the public thread pool for this service.
      enableTXC Specifies whether to enable Global Transaction Service (GTS) for distributed transactions.
      ref Required. The ID of the Spring bean that you want to publish as an HSF service. The data type is ref.
      methodSpecials Optional. The timeout period (unit: ms) for a single method. With this property, different timeout periods can be set for different methods in an interface. This timeout property takes precedence over clientTimeout but defers to methodSpecials on the consumer.

      Service creation and publishing restrictions are as follows.

      Name Example Maximum size Adjustable
      {Service name}:{Version number} com.alibaba.edas.testcase.api.TestCase:1.0.0 192 bytes No
      Group name HSF 32 bytes No
      The number of services published for a Pandora application instance. None 800 Yes. On the Basic Information page, you can click Setting on the right of Application Settings and select JVM in the drop-down list. In the Application Settings dialog box, choose Custom > Custom Parameters and enter -DCC.pubCountMax=1200 in the input box. You can change the value of the 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 configuration file 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.
Similar to that for a provider, service property configuration for a consumer consists of the Maven dependency configuration and Spring configuration.
  1. Configure the service properties.
    1. Add the Maven dependencies to the pom.xml file.
    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 target services from the service registry based on 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">
              <! -- 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, which corresponds to the service name of the service provider. The HSF consumer queries and subscribes to services according to the combined criteria of the interface and version.  -->
                  interface="com.alibaba.edas.carshop.itemcenter.ItemService"
                  <! -- The version that corresponds to the version of the service provider. The HSF consumer queries and subscribes to services according to the combined criteria of the interface and version.  -->
                  version="1.0.0">
              </hsf:consumer>
      </beans>
  2. Configure the service consumer.
    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 according to 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 as needed by referring to the service consumer properties in the following table.

    Property Description
    interface Required. The interface of the service to be called. The data type is String.
    version Optional. The version of the service to be called. The default value is 1.0.0. The data type is String.
    methodSpecials Optional. The timeout period (unit: ms) for a single method. With this property, different timeout periods can be set for different methods in an interface. This timeout property takes precedence over that of the service provider.
    target This property is used in the unit testing environment and development environment to manually specify the address of the service provider. If you want to specify the address of the provider based on the target service address pushed by the configuration center, you can set -Dhsf.run.mode to 0 on the consumer.
    connectionNum Optional. The maximum number of connections to the server. Default value: 1. If you want to transmit a small amount of data with a shorter delay, set this property to a larger value to improve transactions per second (TPS).
    clientTimeout The timeout period set by the consumer for all methods in an interface, in milliseconds. Timeout settings are sorted in descending order of priority as follows: consumer methodSpecials, consumer interface level, provider methodSpecials, and provider interface level.
    asyncallMethods Optional. The list of methods for asynchronous calls on the service. The default value is null, indicating that all methods are used for synchronous calls.
    maxWaitTimeForCsAddress The 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 no longer waits and proceeds with initialization. This parameter is only used to call a service during application initialization. As this parameter extends the startup time, we recommend that you do not use this parameter when no other services need to be called.
    Configuration example of consumer service 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 locally

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

During development environment configuration, you can add the following JVM startup properties used to change the behavior of HSF。

Property Description
-Dhsf.server.port The port for starting HSF services. The default value is 12200.
-Dhsf.serializer The serialization method of HSF. The default value is hessian.
-Dhsf.server.max.poolsize The maximum size of the thread pool of the HSF provider. The default value is 720.
-Dhsf.server.min.poolsize The minimum size of the thread pool of the HSF provider. The default value is 50.
-DHSF_SERVER_PUB_HOST The IP address for providing services over the Internet. If this property is not set, the value of -Dhsf.server.ip is used.
-DHSF_SERVER_PUB_PORT The port for providing services over the Internet, which must be listened to on the local host and be authorized for access. The value of -Dhsf.server.port is used by default. If -Dhsf.server.port is not configured, the value 12200 is used by default.

Query HSF services locally

During development and debugging, if your service is registered by using the light-weight configuration registry, you can query the services provided or called by an application in the EDAS console.

Assume that you start the EDAS configuration center on an Elastic Compute Service (ECS) instance whose IP address is 192.168.1.100.
  • Access http://192.168.1.100:8080/.
  • In the left-side navigation pane, click Services. Set Service Name, Service Group Name, or IP Address 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 registry address by default. If the ECS instance of the developer has multiple NICs, set the SERVER_IP variable in the startup script to explicitly bind an address.

Common query cases

  • Providers tab
    • Enter the IP address in the search box and click Search to query the services provided by the host with the specified IP address.
    • Enter the service name or service group name in the search box 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 Search to query the services called by the host with the specified IP address.
    • Enter the service name or service group name in the search box to search for the IP address of the host that calls the service.

Deploy applications to EDAS

Local applications that use the light-weight configuration registry can be directly deployed to EDAS without any modification, and the registry is automatically replaced with the EDAS registry.

To pack a WAR package that can run in EDAS Container, you need to 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 local program into a WAR file.

Select EDAS Container for the application runtime environment.

For more information, see Deploy applications in ECS clusters and Use an image to deploy an application in a Container Service Kubernetes cluster.