SOFARPC Quick Start

更新时间:
复制 MD 格式

SOFAStack Microservice uses SOFARPC to publish and reference services, and other microservice modules are also built around it. This topic describes the entire process from local development to cloud deployment, showing you how to implement SOFARPC locally, publish it to the cloud, and manage services. The sample project also supports direct connections, allowing you to test SOFARPC service publishing and referencing on your local machine before deploying to the cloud.

Local project development

SOFARPC project development flowchart

RPC 流程图.png

SOFARPC sample code demo video

Preparations

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

    Important

    Only SpringBoot and SOFABoot applications are currently supported.

  • Generate two SOFABoot Web projects: one to act as the service provider and the other as 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 the download is complete, refer to the Version Guide to update the version number in the pom.xml file in the project's root directory to the latest version.

Local development process

  1. Import dependencies.

    If you created a project by following the preceding steps, this dependency is included by default and you can skip this step. If you downloaded the sample project, you must import the SOFARPC Maven dependency into the pom.xml file of the Web module for both SOFABoot projects.

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

    The business logic 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 SampleService.java, and the interface path is com.alipay.samples.rpc.SampleService.

        public interface SampleService{
           public String hello();
        }
      • Write the service implementation class

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

        @Service
        @SofaService(interfaceType =SampleService.class,bindings =@SofaServiceBinding(bindingType ="bolt"))
        public class SampleServiceImpl implements SampleService{
           private int count =0;
        
           @Override
           public String hello(){
              return "Hello SOFARpc! times = "+ count++;
           }
        }
    • Business logic for service referencing

      • Inject the reference object

        This example uses the ReferenceHolder class to manage all reference objects, as shown below:

        @Component
        public class ReferenceHolder {
            @SofaReference(interfaceType = SampleService.class, binding = @SofaReferenceBinding(bindingType = "bolt", directUrl = "127.0.0.1:12201"))
            private SampleService sampleService;
        
            public SampleService getSampleService() {
                return sampleService;
            }
        
            public void setSampleService(SampleService sampleService) {
                this.sampleService = sampleService;
            }
        }
        Note

        The port number 12201 in directUrl="127.0.0.1:12201" must match the rpc.tr.port=12201 setting in the src/main/resources/config/application.properties file of the myserver-app Web module.

      • Referenced object

        For ease of use, this example places the service reference logic in the com.alipay.mytestsofa.SOFABootWebSpringApplication class of the myclient-app project's Web module, as shown below:

        @SpringBootApplication
        public class SOFABootWebSpringApplication{
            private static final Logger logger =LoggerFactory.getLogger(SOFABootWebSpringApplication.class);
        
            public static void main(String[] args){
                //*************** Note ******************//
                // When you start myserver-app and myclient-app locally at the same time, a Tomcat port conflict occurs. You must change the port number of myclient-app to 8084.
                // When you publish myserver-app and myclient-app to the cloud, the default health check port is 8080. You must comment out this line.
                System.setProperty("server.port","8084");
                // Because a local startup does not have a service registry, use a direct connection to access the locally started myserver-app. You must comment out this line when you publish to the cloud.
                System.setProperty("run.mode","TEST");
                //********************************//
        
                SpringApplication springApplication =new SpringApplication(SOFABootWebSpringApplication.class);
                ApplicationContext applicationContext = springApplication.run(args);
        
                if(logger.isInfoEnabled()){
                    printMsg("SofaRpc Application (myclient-app) started on 8084 port.");
                }
        
                // Call the SOFARPC service.
                ReferenceHolder referenceHolder = applicationContext.getBean(ReferenceHolder.class);
                final SampleService sampleService = referenceHolder.getSampleService();
        
                new Thread(new Runnable(){
                    @Override
                    public void run(){
                        while(true){
                            try{
                                String response = sampleService.hello();
                                printMsg("Response from myserver-app: "+ response);
                            }catch(Exception e){
                                e.printStackTrace();
                            }finally{
                                try{
                                    TimeUnit.SECONDS.sleep(3);
                                }catch(InterruptedException e){
                                }
                            }
        
                        }
        
                    }
                }).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, which defaults to 12200. TR stands for TaobaoRemoting, the underlying communication framework used by RPC. This configuration is not required for cloud deployment.

    2. Run SOFABootWebSpringApplication in the Web submodule.

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

      System.setProperty("server.port","8083");
      Important

      Before you publish myserver-app to the cloud, 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, which defaults to 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.

      • instanceId (instance identity): The unique identity of an application instance in a workspace.

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

      • AntVIP endpoint: The unique identifier for a region. Each region has one address.

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

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

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

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

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

    3. Configure the run mode and environment, as shown below:

      run.mode=NORMAL
      com.alipay.env=shared
    4. Configure the parameters 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 how SOFARPC works.

Sample overview

Open the myserver-app and myclient-app projects in rpc-demo using IDEA or Eclipse.

Key information for the sample project

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

  • artifactId: The project's artifact identifier. In the sample project, it is myserver-app or myclient-app.

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

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

Bean configuration for the sample project

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

  • Service publishing example

    @SofaService(interfaceType =SampleService.class,bindings =@SofaServiceBinding(bindingType ="bolt"))
  • Service referencing example

    @SofaReference(interfaceType =SampleService.class,binding =@SofaReferenceBinding(bindingType ="bolt",directUrl ="127.0.0.1:12201"))
    privateSampleService sampleService;
    Note

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

How the sample project works

  • Both projects provide the same service interface and implementation in the same location within their endpoint modules. The service is discovered through annotations, and the two projects are associated through the shared interface, with one project acting as the client and the other as the server. For local testing, you can configure `directUrl` to discover the service through a direct connection. For server deployments, the service is discovered through the Direct Server Return (DSR) foundation.

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

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

Verify the service in the sample project

  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:HelloSOFARpc! times = xx

    You can also verify the service reference in the logs. You can set the log path in the src/main/resources/config/application.properties file of the Web submodule. By default, the service reference result is available in logs/myweb-app/common-default.log.

Application packaging and cloud deployment

  1. Package the local application.

    For the procedure, see Run locally.

  2. Publish the application.

    • For the overall application publishing flow, see Technology stack guide.

    • For detailed steps on publishing the application, see the following documents based on the deployment method:

Service management

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