Quick Start for REST services

更新时间:
复制 MD 格式

SOFAStack Microservice uses SOFARPC to publish and reference services that support the REST protocol. This topic guides you through the entire process, from local development to cloud deployment. You will learn how to implement SOFAREST features, publish an application, and manage services in the cloud. This topic also explains the implementation principles of SOFAREST. The sample project supports direct connections, which lets you test publishing and referencing SOFAREST services on your local machine.

Local project development

SOFAREST project development flowchart

REST流程图.png

SOFAREST sample code demo video

Preparations

  • Set up the SOFABoot environment. For more information, see Set up an environment.

  • Generate two SOFABoot web projects to act as the service provider and the service consumer. You can use one of the following methods:

    • Create two SOFABoot web projects. For more information, see Create a project.

    • Download the sample project. After you download the project, see Version Guide and change the version number in the pom.xml file in the project's root directory to the latest version.

Local development procedure

  1. Import dependencies.

    Projects created step-by-step already include this dependency by default. You can skip this step for those projects. If you downloaded the sample project, add the SOFARPC Maven dependency to the pom.xml file of the web module in both local SOFABoot projects.

    <dependency>
        <groupId>com.alipay.sofa</groupId>
        <artifactId>rpc-enterprise-sofa-boot-starter</artifactId>
    </dependency>
  2. Write the business logic.

    This step involves publishing and referencing services. This example uses annotations to configure beans for service publishing and referencing. For more information, see Use annotations. For other configuration methods, see Use XML configuration and Use programming APIs.

    • Business logic for service publishing

      • Design the service interface class

        In this example, the class is named SampleRestFacade.java, and the interface path is com.alipay.samples.rpc.SampleRestFacade.

        @Path("/sofarest")  // Note the inheritance of this annotation. If this annotation is missing from the implementation class or method, a SOFAREST call may result in a 404 error.
        @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
        @Produces(MediaType.APPLICATION_JSON +";charset=UTF-8")
        public interface SampleRestFacade{
            /**
            * http://localhost:8341/sofarest/hello
            */
            @GET
            @Path("/hello")
            public String hello();
        }
      • Write the service implementation class

        In this example, the class is named SampleRestFacadeImpl.java, and the interface implementation path is com.alipay.samples.rpc.impl.SampleRestFacadeImpl.

        @Service
        @SofaService(interfaceType =SampleRestFacade.class,bindings =@SofaServiceBinding(bindingType ="rest"))
        public class SampleRestFacadeImpl implements SampleRestFacade{
              private int count =0;
        
              public SampleRestFacadeImpl(){
                  System.out.println("print start");
              }
        
             @Override
             public String hello(){
                  return "Hello SOFARest! times = "+ count++;
             }
        }   
    • Service reference logic

      • Inject the reference object

        This example uses the ReferenceHolder class to manage reference objects:

        @Component
        public class ReferenceHolder{
              @SofaReference(interfaceType =SampleRestFacade.class, binding =@SofaReferenceBinding(bindingType ="rest",directUrl ="127.0.0.1:8341"))
              private SampleRestFacade sampleRestFacade;
              public SampleRestFacade getSampleRestFacade(){
                  return sampleRestFacade;
              }
             public void setSampleRestFacade(SampleRestFacade sampleRestFacade){
                 this.sampleRestFacade = sampleRestFacade;
             }
        }
        Note

        The bindingType is the REST protocol, and the direct connection port is 8341. Therefore, directUrl="127.0.0.1:8341".

      • Reference the object

        For ease of use, this example places the service reference logic in com.alipay.mytestsofa.SOFABootWebSpringApplication within the web module of the myclient-app project, as shown in the following code:

        @SpringBootApplication
        public class SOFABootWebSpringApplication{
             private static final Logger logger =LoggerFactory.getLogger(SOFABootWebSpringApplication.class);
        
             public static void main(String[] args){
                   //*************** Note ******************//
                  // When starting myserver-app and myclient-app locally at the same time, change the port number of myclient-app to 8084 to avoid a Tomcat port conflict.
                  // When publishing myserver-app and myclient-app to a cloud environment, comment out this line because the default health check port is 8080.
                 System.setProperty("server.port","8084");
                 // Because there is no service registry for a local startup, use a direct connection to access the locally started myserver-app. Comment out this line when publishing to a production environment.
                 System.setProperty("run.mode","TEST");
                 //********************************//
        
                 SpringApplication springApplication =newSpringApplication(SOFABootWebSpringApplication.class);
                 ApplicationContext applicationContext = springApplication.run(args);
        
                  if(logger.isInfoEnabled()){
                        printMsg("SofaRpc Application (myclient-app) started on 8084 port.");
                  }
        
                  ReferenceHolder referenceHolder = applicationContext.getBean(ReferenceHolder.class);
                  // Call the SOFAREST service.
                 final SampleRestFacade sampleRestFacade = referenceHolder.getSampleRestFacade();
        
                  new Thread(new Runnable(){
                     @Override
                     public void run(){
                          while(true){
                                  try{
                                           String response = sampleRestFacade.hello();
                                           printMsg("Response from myserver-app.rest: "+ response);
                                  }catch(Exception e){
                                         e.printStackTrace();
                                  }finally{
                                         try{
                                                 TimeUnit.SECONDS.sleep(3);
                                          }catch(InterruptedException e){
                                              //ignore
                                         }
                                    }
                              }
                         }
                  }).start();
              }
             private static void printMsg(String msg){
                  System.out.println(msg);
                   if(logger.isInfoEnabled()){
                         logger.info(msg);
                    }
             }
        }
  3. Configure package scanning.

    @SpringBootApplication(scanBasePackages ={"com.alipay.mytestsofa","com.alipay.samples.rpc"})
    public class SOFABootWebSpringApplication{
    ...
    }
  4. Configure ports for local execution.

    1. In the application.properties file of the myserver-app web module, set rpc.tr.port=12201.

      rpc.tr.port is the TR port number. The default value is 12200. TR stands for Taobao Remoting, which is the underlying communication framework used by the RPC service. This configuration is not required for cloud deployment.

    2. Run SOFABootWebSpringApplication in the web submodule.

      After you run the application, the framework automatically publishes the service. To avoid port conflicts, you must specify the port in this class.

      Important

      Before you publish myserver-app to a cloud environment, you must comment out the configuration for port 8083 in the code.

    3. In the application.properties file of the myclient-app web module, set rpc.tr.port=12202.

      rpc.tr.port is the TR port number. The default value is 12200. This configuration is not required for cloud deployment.

  5. Configure application.properties.

    1. Log on to the SOFAStack console.

    2. In the navigation pane on the left, choose Middleware > Middleware Overview.

      Obtain the following information:

      • instanceld (instance identity): The unique identity of the application instance in the workspace.

        The corresponding key in the application.properties file is com.alipay.instanceid.

      • AntVIP endpoint: The unique identifier for a region. Each region has one address. Applications use the AntVIP to find the address of the environment in their region. The AntVIP address values for different environments are as follows:

        • Hangzhou Gold Zone: cn-hangzhou-fin-middleware-acvip-prod.cloud.alipaycs.net

        • Shanghai Non-Gold Zone: cn-shanghai-middleware-acvip-prod.cloud.alipaycs.net

        • Shanghai Gold Zone: cn-shanghai-fin-sofastack-middleware-acvip-prod.cloud.alipaycs.net

        • Hangzhou Non-Gold Zone: cn-hangzhou-middleware-acvip-prod.cloud.alipaycs.net

        The corresponding key in the application.properties file is com.antcloud.antvip.endpoint.

      • Access Key ID: Used to identify the user. Click Get AK to go to the RAM console to obtain the ID. For more information, see Create an AccessKey.

        The corresponding key in the application.properties file is com.antcloud.mw.access.

      • Access Key Secret: Used to authenticate the user. Click Get SK to go to the RAM console to obtain the secret. For more information, see Create an AccessKey.

        The corresponding key in the application.properties file is com.antcloud.mw.secret.

    3. Configure the run mode and environment, as shown in the following example:

      run.mode=NORMAL
      com.alipay.env=shared
    4. Configure the parameters that you obtained in the previous steps in the application.properties file.

    Note

    For more information, see Import SOFA middleware.

Sample project

The following section uses the sample project to explain the implementation principles of SOFARPC.

Sample overview

Open the myserver-app and myclient-app projects in the rpc-demo using an IDE, such as IDEA or Eclipse.

Key information for the sample project

  • groupId: The unique identifier for the project organization. In the sample project, this is com.alipay.mytestsofa.

  • artifactId: The artifact identifier for the project. In the sample project, this is myserver-app or myclient-app.

  • version: The version number. The default value is 1.0-SNAPSHOT.

  • package: The application package name. By default, it is the same as the groupId. In the sample project, this is com.alipay.mytestsofa.

Sample project bean configuration

Bean configuration is divided into two types: service publishing and service referencing:

  • Example of service publishing

    @SofaService(interfaceType =SampleRestFacade.class,bindings =@SofaServiceBinding(bindingType ="rest"))
  • Example of service referencing

    @SofaReference(interfaceType =SampleRestFacade.class, binding =@SofaReferenceBinding(bindingType ="rest",directUrl ="127.0.0.1:8341"))
    private SampleRestFacade sampleRestFacade;
    Note

    In this example, the ReferenceHolder class is created to manage all instances to be referenced.

REST implementation in the sample project

SOFAREST is implemented based on SOFARPC. The implementation principles of SOFARPC are as follows:

  • Provide the same service interface and implementation in the same location within the endpoint modules of both projects. The service is discovered through annotations. The two projects are associated through the same interface. One project acts as the client and the other as the server. For a local project, the service is discovered through a direct connection by configuring the directUrl during referencing. For a server deployment, the service is discovered through the Direct Server Return (DSR) base.

  • Start SOFABootWebSpringApplication in the myserver-app web module to publish the service.

  • Start SOFABootWebSpringApplication in the myclient-app web module to reference the service.

Validating the sample project service

  1. Start SOFABootWebSpringApplication in the myserver-app web module to publish the service.

  2. Start SOFABootWebSpringApplication in the myclient-app web module to reference the service.

    After the service is successfully referenced, the myclient-app console displays the following output:

    Response from myserver-app.rest:HelloSOFARest! times = xx

    Access http://localhost:8341/sofarest/hello in a local browser. The output shows the number of times the client has called the service when you access the URL.

    HelloSOFARest! times = xx

After cloud deployment, you can run the curl http://{Server IP address}:8341/sofarest/hello command in the client command line to verify the service.

You can also check the service reference results in the logs. By default, the results are in /logs/myclient-app/common-default.log. You can change the log path in the src/main/resources/config/application.properties file of the web submodule.

Application packaging and cloud deployment

  1. Package the local application.

    For more information about the procedure, see Run locally.

  2. Publish the application.

    • For more information about the overall application publishing process, see Technology stack guide.

    • For detailed steps on how to publish the application, see the following documents based on the deployment method:

Service management

On the Service Management page, you can query and manage the published RPC services. For more information, see View services.服务查询