All Products
Search
Document Center

Develop applications with EDAS SDK

Last Updated: Aug 06, 2019

Quick start

This topic describes how to use EDAS SDK to quickly develop applications in HSF.

Download demo projects

Code described in this topic can be obtained from the official demo.

  1. Download Demo projects.

  2. Decompress the downloaded package and locate the carshop folder, where you can see the following Maven project subfolders: itemcenter-api, itemcenter, and detail.

    • itemcenter-api: provides the API definition.
    • itemcenter: specifies the service provider application.
    • detail: specifies the service consumer application.

Note: Use JDK 1.7 or later.

Define service APIs

HSF services are implemented based on APIs. After an API is defined, the provider can implement a specific service over this API. The consumer also subscribes to the service over this API.

In the itemcenter-api project in demo, the service API com.alibaba.edas.carshop.itemcenter.ItemService is defined and has the following content:

  1. public interface ItemService {
  2. public Item getItemById(long id);
  3. public Item getItemByName(String name);
  4. }

The service API provides two methods: getItemById and getItemByName.

Develop provider services

The provider implements service APIs to provide specific services.Because the Spring framework is used for development, you also need to configure service attributes in the .xml file.

Note: The itemcenter folder in the demo project contains the sample code of a provider service.

Implement a service API

Implement a service API by referring to the example in the ItemServiceImpl.java file:

  1. package com.alibaba.edas.carshop.itemcenter;
  2. public class ItemServiceImpl implements ItemService {
  3. @Override
  4. public Item getItemById( long id ) {
  5. Item car = new Item();
  6. car.setItemId( 1l );
  7. car.setItemName( "Mercedes Benz" );
  8. return car;
  9. }
  10. @Override
  11. public Item getItemByName( String name ) {
  12. Item car = new Item();
  13. car.setItemId( 1l );
  14. car.setItemName( "Mercedes Benz" );
  15. return car;
  16. }
  17. }

Configure service attributes

The preceding example implements the service API com.alibaba.edas.carshop.itemcenter.ItemService and returns an Item object to both methods.After developing code, configure general items and add Maven dependencies in the web.xml file. Then, use the <hsf /> tag in the Spring configuration file to register and publish the service.This procedure is as follows:

  1. Add the following Maven dependency to the pom.xml file:

    1. <dependencies>
    2. <! -- Add Servlet dependency -->
    3. <dependency>
    4. <groupId>javax.servlet</groupId>
    5. <artifactId>servlet-api</artifactId>
    6. <version>2.5</version>
    7. <scope>provided</scope>
    8. </dependency>
    9. <! -- Add Spring dependency -->
    10. <dependency>
    11. <groupId>com.alibaba.edas.carshop</groupId>
    12. <artifactId>itemcenter-api</artifactId>
    13. <version>1.0.0-SNAPSHOT</version>
    14. </dependency>
    15. <! -- Add service API dependency -->
    16. <dependency>
    17. <groupId>org.springframework</groupId>
    18. <artifactId>spring-web</artifactId>
    19. <version>2.5.6 (or later)</version>
    20. </dependency>
    21. <! -- Add edas-sdk dependency -->
    22. <dependency>
    23. <groupId>com.alibaba.edas</groupId>
    24. <artifactId>edas-sdk</artifactId>
    25. <version>1.5.0</version>
    26. </dependency>
    27. </dependencies>
  2. Add the HSF-specific Spring configuration items to the hsf-provider-beans.xml file.

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:hsf="http://www.taobao.com/hsf"
    4. xmlns="http://www.springframework.org/schema/beans"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    7. http://www.taobao.com/hsf
    8. http://www.taobao.com/hsf/hsf.xsd" default-autowire="byName">
    9. <! -- Define the implementation of the service -->
    10. <bean id="itemService" class="com.alibaba.edas.carshop.itemcenter.ItemServiceImpl" />
    11. <! -- Use the hsf:provider tag to provide a service provider. -->
    12. <hsf:provider id="itemServiceProvider"
    13. <! -- Use the interface attribute to indicate that the service is an implementation of the class. -->
    14. interface="com.alibaba.edas.carshop.itemcenter.ItemService"
    15. <! -- Spring object implemented by the service -->
    16. ref="itemService"
    17. <! -- Version of the published service, which is user-defined and is 1.0.0 by default. -->
    18. version="1.0.0"
    19. </hsf:provider>
    20. </beans>

    The preceding example uses basic configuration items for demonstration purposes. To add other configuration items, refer to the following list of provider service attributes.

List of provider service attributes

Attribute Description
interface This string-format attribute is required and indicates the service API provided for external applications.
version This string-format attribute is optional and indicates the version of the service, which is 1.0.0 by default.
clientTimeout This attribute applies to all methods in the API. However, if the client sets a timeout period for a method using the MethodSpecials attribute, the timeout period configured on the client prevails over that defined for the method.Other methods are not affected by this attribute and still use the timeout period configured on the server.
serializeType This attribute is optional and indicates the serialization type. Its value is in string format and can be hessian (default) or java.
corePoolSize This attribute is used to repurpose part of the public thread pool as the core thread pool dedicated to this service.
maxPoolSize This attribute is used to repurpose part of the public thread pool as the maximum thread pool dedicated to this service.
enableTXC This attribute enables distributed transaction GTS.
ref This ref-format attribute is required and indicates the ID of the Spring bean to be published as an HSF service.
methodSpecials This attribute is optional and used to configure a timeout period (in ms) for each method. With this attribute, different timeout periods can be applied to different methods in an API.This timeout attribute takes precedence over clientTimeout but defers to MethodSpecials on the client.

Example of configuration of provider service attributes

  1. <bean id="impl" class="com.taobao.edas.service.impl.SimpleServiceImpl" />
  2. <hsf:provider id="simpleService" interface="com.taobao.edas.service.SimpleService"
  3. ref="impl" version="1.0.1" clientTimeout="3000" enableTXC="true"
  4. serializeType="hessian">
  5. <hsf:methodSpecials>
  6. <hsf:methodSpecial name="sum" timeout="2000" />
  7. </hsf:methodSpecials>
  8. </hsf:provider>

Develop consumer services

Service subscription for consumers is coded in two steps:

  1. Define a bean using the <hsf:consumer/> tag in the Spring configuration file;
  2. Retrieve the bean from the Spring context to locate the service.

Note: The detail folder in the demo project provides the sample code of a consumer service.

Configure service attributes

Similar to that for providers, service attribute configuration for consumers consists of the Maven dependency configuration and Spring configuration.

  1. Add the Maven dependency to the pom.xml file.

    The Maven dependency configuration of a consumer is the same as that of a provider. For more information, see Configure service attributes in “Develop provider services.”

  2. Add the HSF-specific Spring configuration items to the hsf-consumer-beans.xml.

    Add the consumer definition to the Spring configuration file. The HSF framework subscribes to services in the service center according to the configuration file.

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:hsf="http://www.taobao.com/hsf"
    4. xmlns="http://www.springframework.org/schema/beans"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    7. http://www.taobao.com/hsf
    8. http://www.taobao.com/hsf/hsf.xsd" default-autowire="byName">
    9. <! -- Example of service consumption-->
    10. <hsf:consumer
    11. <! -- Indicates the Bean ID for retrieving the consumer object by code injection -->
    12. id="item"
    13. <! -- Indicates the service name that corresponds to the service name of the service provider. HSF queries and subscribes to services according to the combined criteria of interface and version. -->
    14. interface="com.alibaba.edas.carshop.itemcenter.ItemService"
    15. <! -- Indicates the version that corresponds to the version of the service provider. HSF queries and subscribes to services according to the combined criteria of interface and version. -->
    16. version="1.0.0"
    17. </hsf:consumer>
    18. </beans>

Configure service calls

You can configure a service call by referring to the example in the StartListener.java file:

  1. public class StartListener implements ServletContextListener{
  2. @Override
  3. public void contextInitialized( ServletContextEvent sce ) {
  4. ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext( sce.getServletContext() );
  5. // Retrieve the subscribed services according to the bean ID "item" in Spring configurations.
  6. final ItemService itemService = ( ItemService ) ctx.getBean( "item" );
  7. // Call the getItemById method of ItemService.
  8. System.out.println( itemService.getItemById( 1111 ) );
  9. // Call the getItemByName method of ItemService.
  10. System.out.println( itemService.getItemByName( "myname is le" ) );
  11. }
  12. }

The preceding example uses basic configuration items for demonstration purposes. To add other configuration items, refer to the following list of service attributes.

List of consumer service attributes

Attribute Description
interface This string-format attribute is required and indicates the API of the service to be called.
version This string-format attribute is optional and indicates the version of the service to be called, which is 1.0.0 by default.
methodSpecials This attribute is optional and used to configure a timeout period (in ms) for each method.With this attribute, you can apply different timeout periods to different methods in an API. This timeout attribute takes precedence over the timeout setting of the provider.
target This attribute is primarily used in unit testing and development environments to manually specify the address of the service provider.To specify the address of the provider based on the target service address information pushed from the configuration center, you can specify -Dhsf.run.mode=0 on the consumer.
connectionNum This attribute is optional and set to 1 by default. It indicates the maximum number of connections to the server.To improve TPS, set this attribute to a larger value to minimize the delay of transferring small amounts of data.
clientTimeout This attribute indicates the same timeout period (in ms) set for all methods in an API by the consumer.Timeout settings are sorted in descending order of priority as follows: consumer MethodSpecials, consumer API level, provider MethodSpecials, and provider API level.
asyncallMethods This list-format attribute is optional and indicates that the asynchronously called method name list and asynchronous calls are required for calling the service.This attribute is an empty set by default, which indicates that all methods are called synchronously.
maxWaitTimeForCsAddress This attribute indicates the time during which the thread is blocked to wait for address push when a service is subscribed. Otherwise, the address may not be found due to empty address when the service is called.If the address is not pushed before the blocking time expires, the thread no longer waits and continues initializing subsequent content.
Note: 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 attributes

  1. <hsf:consumer id="service" interface="com.taobao.edas.service.SimpleService"
  2. version="1.1.0" clientTimeout="3000"
  3. target="10.1.6.57:12200?_TIMEOUT=1000" maxWaitTimeForCsAddress="5000">
  4. <hsf:methodSpecials>
  5. <hsf:methodSpecial name="sum" timeout="2000" ></hsf:methodSpecial>
  6. </hsf:methodSpecials>
  7. </hsf:consumer>

Publish services

After coding, API development, and service configuration, you can directly run the service using Ali-Tomcat in Eclipse or IntelliJ IDEA (for more information, see Configure the Eclipse development environment and Configure the IDEA development environment in Prepare development tools.

The following table lists additional JVM startup parameters that you can configure in the development environment to change HSF behaviors:

Attribute Description
-Dhsf.server.port Indicates the port bound to the HSF startup service, which is port 12200 by default.
-Dhsf.serializer Indicates the serialization type of HSF, which is hessian by default.
-Dhsf.server.max.poolsize Indicates the maximum size of the thread pool of the HSF provider, which is 600 by default.
-Dhsf.server.min.poolsize Indicates the minimum size of the thread pool of the HSF provider.The default value is 50.
-DHSF_SERVER_PUB_HOST Indicates the exposed IP address, which uses the value of -Dhsf.server.ip if not configured.
-DHSF_SERVER_PUB_PORT Indicates the exposed port that must be monitored locally and authorized for access. It uses the value of -Dhsf.server.port by default or port 12200 if -Dhsf.server.port is not configured.

Query HSF services in the development environment

During development and debugging, if your service is registered and discovered in the lightweight configuration center, you can query the services provided or called by an application in the EDAS console.

The following assumes that you start the EDAS configuration center on an ECS instance whose IP address is 192.168.1.100.

  1. Go to http://192.168.1.100:8080/.

  2. In the left-side navigation pane, click Service List. On the page that is displayed, enter the service name, service group name, or IP address to search for the service, and view the service provider and caller.

    Note: After the configuration center is started, the address of the first NIC is the service discovery address by default. If the ECS instance of the developer has multiple INCs, set the SERVER_IP variable in the startup script to explicitly bind an address.

Common query cases

Provider list page

  • Enter the IP address in the search condition box and click Search to query the services provided by the instance with the entered IP address.

  • Enter the service name or service group in the search condition box and click Search to query which IP addresses provide the service.

Caller list page

  • Enter the IP address in the search condition box and click Search to query the services called by the instance with the entered IP address.

  • Enter the service name or service group in the search condition box and click Search to query what IP addresses call the service.

Develop advanced features

After following the steps outlined in Quick start, you have developed the basic features of an HSF application. The following section describes how to develop the advanced features of an HSF application based on these basic features.

Download Demos.

Implicit parameter passing (currently, only string-based parameter passing is supported)

Implicit parameter passing is generally used to replace API-based passing for passing simple KV data and it is similar to cookie.

  • Pass a single parameter

    Service consumer:

    RpcContext.getContext().setAttachment("key", "args test");

    Service provider:

    String keyVal=RpcContext.getContext().getAttachment("key");

  • Pass multiple parameters

    Service consumer:

    1. Map<String,String> map=new HashMap<String,String>();
    2. map.put("param1", "param1 test");
    3. map.put("param2", "param2 test");
    4. map.put("param3", "param3 test");
    5. map.put("param4", "param4 test");
    6. map.put("param5", "param5 test");
    7. RpcContext rpcContext = RpcContext.getContext();
    8. rpcContext.setAttachments(map);

    Service provider:

    1. Map<String,String> map=rpcContext.getAttachments();
    2. Set<String> set=map.keySet();
    3. for (String key : set) {
    4. System.out.println("map value:"+map.get(key));
    5. }

    Note: Implicit parameter passing is only valid for a single call. When the consumer call returns the result, the information in RpcContext is cleared automatically.

Asynchronous calls

Asynchronous calls can be made using either the callback or the future method.

  • Callback method

    If the callback method is configured for the consumer, you must configure a listener that implements the HSFResponseCallback API.After the result is returned, HSF calls the method in HSFResponseCallback.

    Note: The listener of the HSFResponseCallback API must not be an internal class. Otherwise, the Pandora classloader returns an error during loading.

    XML configuration:

    1. <hsf:consumer id="demoApi" interface="com.alibaba.demo.api.DemoApi"
    2. version="1.1.2" >
    3. <hsf:asyncallMethods>
    4. <hsf:method name="ayncTest" type="callback"
    5. listener="com.alibaba.ifree.hsf.consumer.AsynABTestCallbackHandler" />
    6. </hsf:asyncallMethods>
    7. </hsf:consumer>

    The AsynABTestCallbackHandler class implements the HSFResponseCallback API.The DemoApi API has the ayncTest method.

    Sample code

    1. public void onAppResponse(Object appResponse) {
    2. //Retrieve the value after the asynchronous call.
    3. String msg = (String)appResponse;
    4. System.out.println("msg:"+msg);
    5. }

    Note:

    • Method names are used to identify methods. Therefore, overloaded methods are not differentiated.Methods sharing the same name are set using the same call method.
    • HSF calls cannot be initiated in a call.Otherwise, the I/O thread is suspended and cannot be recovered.
  • Future method

    If the future method is configured for the consumer, after you make a call, the returned result is retrieved through public static Object getResponse(long timeout) in HSFResponseFuture.

    XML configuration:

    1. <hsf:consumer id="demoApi" interface="com.alibaba.demo.api.DemoApi" version="1.1.2" >
    2. <hsf:asyncallMethods>
    3. <hsf:method name="ayncTest" type="future" />
    4. </hsf:asyncallMethods>
    5. </hsf:consumer>

    The sample code is as follows:

    • Asynchronous processing of a single call:

      1. //Initiate a call.
      2. demoApi.ayncTest();
      3. // Process the service.
      4. ...
      5. //Directly obtain the message. (If the result is not required, you can skip this step.)
      6. String msg=(String) HSFResponseFuture.getResponse(3000);
    • Concurrent processing of multiple calls:

      To process multiple tasks concurrently, retrieve and store the future object and then reuse it after the call.

      1. //Define a set.
      2. List<HSFFuture> futures = new ArrayList<HSFFuture>();
    • Concurrent call within a method:

      1. //Initiate a call.
      2. demoApi.ayncTest();
      3. //Retrieve the future object.
      4. HSFFuture future=HSFResponseFuture.getFuture();
      5. futures.add(future);
      6. //Continue calling other services (asynchronous calling is used).
      7. HSFFuture future=HSFResponseFuture.getFuture();
      8. futures.add(future);
      9. // Process the service.
      10. ...
      11. //Retrieve and process the data.
      12. for (HSFFuture hsfFuture : futures) {
      13. String msg=(String) hsfFuture.getResponse(3000);
      14. //Process corresponding data.
      15. ...
      16. }

Generic calls

Generic calls can combine APIs, methods, and parameters for remote procedure calls (RPCs) without relying on any service APIs.

Step 1: Add the generic attribute to the consumer’s XML configuration.

  1. <hsf:consumer id="demoApi" interface="com.alibaba.demo.api.DemoApi" generic="true"/>

Note: “generic” indicates generic parameters, “true” indicates that generic parameters are supported, and “false” (default) indicates that generic parameters are not supported.

DemoApi API method:

  1. public String dealMsg(String msg);
  2. public GenericTestDO dealGenericTestDO(GenericTestDO testDO);

Step 2: Obtain demoApi to enforce conversion to a generic service.

  1. Import the generic service API

    import com.alibaba.dubbo.rpc.service.GenericService

  2. Retrieve generic objects

    • XML loading method
      1. //In a Web project, you can force service conversion after injection using a Spring bean. This example is a unit test and therefore must load the configuration file.
      2. ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext("hsf-generic-consumer-beans.xml");
      3. //The forced conversion API is GenericService.
      4. GenericService svc = (GenericService) consumerContext.getBean("demoApi");
    • Code subscription method

      1. HSFApiConsumerBean consumerBean = new HSFApiConsumerBean();
      2. consumerBean.setInterfaceName("com.alibaba.demo.api.DemoApi");
      3. consumerBean.setGeneric("true"); // Set generic to true.
      4. consumerBean.setVersion("1.0.0");
      5. consumerBean.init();
      6. // The forced conversion API is GenericService.
      7. GenericService svc = (GenericService) consumerBean.getObject();

Step 3: Implement generic APIs.

  1. Object $invoke(String methodName, String[] parameterTypes, Object[] args) throws GenericException;

Description of API parameters:

  • methodName: indicates the name of the method to be called.

  • parameterTypes: indicates the type of the parameters of the method to be called.

  • args: indicates the parameter value to be passed.

Step 4: Initiate generic calls.

  • String-type parameters

    1. svc.$invoke("dealMsg", new String[] { "java.lang.String" }, new Object[] { "hello" })
  • Object parameters, which must be the same on the provider and consumer

    1. // Construct the entity object GenericTestDO, which has the ID and name attributes.
    2. GenericTestDO genericTestDO = new GenericTestDO();
    3. genericTestDO.setId(1980l);
    4. genericTestDO.setName("genericTestDO-tst");
    5. // Use PojoUtils to generate the POJO description of the second party library.
    6. Object comp = PojoUtils.generalize(genericTestDO);
    7. // Call the service in generic mode.
    8. svc.$invoke("dealGenericTestDO",new String[] { "com.alibaba.demo.generic.domain.GenericTestDO" }, new Object[] { comp });

Trace Filter extension

Download Demos.

Basic APIs

  1. public interface ServerFilter extends RPCFilter {
  2. }
  3. public interface ClientFilter extends RPCFilter {
  4. }
  5. public interface RPCFilter {
  6. ListenableFuture<RPCResult> invoke(InvocationHandler invocationHandler, Invocation invocation) throws Throwable;
  7. void onResponse(Invocation invocation, RPCResult rpcResult);
  8. }

Implementation procedure

  1. Implement ServerFilter to enable interception on the provider.
  2. Implement ClientFilter to enable interception on the consumer.
  3. Use the standard META-INF/services/com.taobao.hsf.invocation.filter.RPCFilter file to register Filter.

Implementation example

  1. import com.taobao.hsf.invocation.Invocation;
  2. import com.taobao.hsf.invocation.InvocationHandler;
  3. import com.taobao.hsf.invocation.RPCResult;
  4. import com.taobao.hsf.invocation.filter.ServerFilter;
  5. import com.taobao.hsf.util.PojoUtils;
  6. import com.taobao.hsf.util.concurrent.ListenableFuture;
  7. public class HSFServerFilter implements ServerFilter {
  8. public ListenableFuture<RPCResult> invoke(InvocationHandler invocationHandler, Invocation invocation) throws Throwable {
  9. //process args
  10. String[] sigs = invocation.getMethodArgSigs();
  11. Object [] args = invocation.getMethodArgs();
  12. System.out.println("#### intercept request");
  13. for(String sig : sigs) {
  14. System.out.print(sig);
  15. System.out.print(";");
  16. }
  17. System.out.println();
  18. for(Object arg : args) {
  19. System.out.println(PojoUtils.generalize(arg));
  20. System.out.print(";");
  21. }
  22. System.out.println();
  23. return invocationHandler.invoke(invocation);
  24. }
  25. public void onResponse(Invocation invocation, RPCResult rpcResult) {
  26. System.out.println("#### intercept response");
  27. Object resp = rpcResult.getHsfResponse().getAppResponse();
  28. System.out.println(PojoUtils.generalize(resp));
  29. }
  30. }

Configure META-INF/services/com.taobao.hsf.invocation.filter.RPCFilter

  1. com.alibaba.edas.carshop.itemcenter.filter.HSFServerFilter

Running effect

  1. #### intercept request
  2. long
  3. 1111

intercept response

  1. {itemId=1, itemName=Mercedes Benz, class=com.alibaba.edas.carshop.itemcenter.Item}

Optional Filter

In some scenarios, if you have customized the Filter but want to apply it only to certain services, use an optional Filter.To do this, annotate Filter with @Optional, as shown below:

  1. ```
  2. @Optional
  3. @Name("HSFOptionalServerFilter")
  4. public class HSFOptionalServerFilter implements ServerFilter {
  5. public ListenableFuture<RPCResult> invoke(InvocationHandler invocationHandler,
  6. Invocation invocation) throws Throwable {
  7. System.out.println("#### HSFOptionalServerFilter intercept request");
  8. return invocationHandler.invoke(invocation);
  9. }
  10. public void onResponse(Invocation invocation, RPCResult rpcResult) {
  11. System.out.println("#### HSFOptionalServerFilter intercept response");
  12. }
  13. }
  14. ```

When a specific service needs to use this Filter, simply advertise the service on the configured bean, as shown below:

  1. <bean class="com.taobao.hsf.app.spring.util.HSFSpringProviderBean">
  2. <property name="serviceInterface" value="com.alibaba.middleware.hsf.guide.api.service.OrderService" />
  3. <property name="version" value="1.0.0" />
  4. <property name="group" value="HSF" />
  5. <property name="includeFilters">
  6. <list>
  7. <value>HSFOptionalServerFilter</value>
  8. <value>NoFilter</value>
  9. </list>
  10. </property>
  11. <property name="target" ref="orderService" />
  12. </bean>

In the preceding configuration, all the ServerFilters without the @Optional modifier, including HSFOptionalServerFilter and NoFilter, are used. The name of HSFOptionalServerFilter comes from the @Name modifier configured in the corresponding Filter.

  1. If the Filter with this name cannot be found, the system displays a prompt, but you still can start or run this Filter.

Perform the unit test

There are two unit test methods in the test environment.

Method 1: Publish and subscribe to services using the LightApi code

Method 2: Publish and subscribe to services using XML configuration

For demos, click Demo download.

Method 1: Publish and subscribe to services using the LightApi code

  1. Add LightApi dependency to Maven.

    1. <dependency>
    2. <groupId>com.alibaba.hsf</groupId>
    3. <artifactId>LightApi</artifactId>
    4. <version>1.0.0</version>
    5. </dependency>

    Note: Please use 1.0.5 or later version of LightApi, or hsf: can not load class {com.taobao.hsf.address.AddressService} after all phase error may appear.

  2. Create ServiceFactory.

    The Pandora address must be set, and the parameter indicates the directory where the SAR package is located.If the SAR package address is /Users/Jason/Work/AliSoft/PandoraSar/DevSar/taobao-hsf.sar the parameter is as follows:

    1. private static final ServiceFactory factory = ServiceFactory.getInstanceWithPath("/Users/Jason/Work/AliSoft/PandoraSar/DevSar");
  3. Use codes to publish and subscribe to the service.

    1. // Publish the service (you can skip this step if the publisher already exists.)
    2. factory.provider("helloProvider")// This parameter is an identifier. After initialization, you can call provider("helloProvider") to retrieve the corresponding service.
    3. .service("com.alibaba.edas.unit.service.UnitTestService")// Fully-Qualified Class Name (FQCN) of the API
    4. .version("1.0.0")// Version
    5. .impl(new UnitTestServiceImpl())// Corresponding service implementation
    6. .publish();// Publish the service by calling at least service() and version().
    7. // Consume the service.
    8. factory.consumer("helloConsumer")// This parameter is an identifier. After initialization, you can call consumer("helloConsumer") to retrieve the corresponding service.
    9. .service("com.alibaba.edas.unit.service.UnitTestService")// FQCN of the API
    10. .version("1.0.0")// Version
    11. .subscribe();
    12. factory.consumer("helloConsumer").sync();// Synchronously wait for address push for up to 6 seconds.
    13. UnitTestService log4jService = (UnitTestService) factory.consumer("helloConsumer").subscribe();// Retrieve the corresponding service using the ID. The subscribe() method returns the corresponding API.
    14. // Call the service method.
    15. System.out.println("bean -> msg rec success:-"+log4jService.print());

Method 2: Publish and subscribe to services using XML configuration

  1. Complete the XML configuration of HSF.

  2. Load the configuration file using code.

    1. //Load the service provider using XML.
    2. new ClassPathXmlApplicationContext("hsf-provider-beans.xml");
    3. //Load the service consumer using XML.
    4. ClassPathXmlApplicationContext consumerContext=new ClassPathXmlApplicationContext("hsf-consumer-beans.xml");
    5. //Retrieve the bean.
    6. UnitTestXMLConsumer unitTestXMLConsumer=(UnitTestXMLConsumer) consumerContext.getBean("unitTestConsumer");
    7. //Call the service.
    8. unitTestXMLConsumer.testUnitProvider();