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

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.xmlfile in the project's root directory to the latest version.
Local development procedure
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.xmlfile of the web module in both local SOFABoot projects.<dependency> <groupId>com.alipay.sofa</groupId> <artifactId>rpc-enterprise-sofa-boot-starter</artifactId> </dependency>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 iscom.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 iscom.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
ReferenceHolderclass 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; } }NoteThe 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.SOFABootWebSpringApplicationwithin the web module of themyclient-appproject, 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); } } }
Configure package scanning.
@SpringBootApplication(scanBasePackages ={"com.alipay.mytestsofa","com.alipay.samples.rpc"}) public class SOFABootWebSpringApplication{ ... }Configure ports for local execution.
In the
application.propertiesfile of themyserver-appweb module, setrpc.tr.port=12201.rpc.tr.portis 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.Run
SOFABootWebSpringApplicationin 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.
ImportantBefore you publish
myserver-appto a cloud environment, you must comment out the configuration for port 8083 in the code.In the
application.propertiesfile of themyclient-appweb module, setrpc.tr.port=12202.rpc.tr.portis the TR port number. The default value is 12200. This configuration is not required for cloud deployment.
Configure
application.properties.Log on to the SOFAStack console.
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.propertiesfile iscom.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.netShanghai Non-Gold Zone:
cn-shanghai-middleware-acvip-prod.cloud.alipaycs.netShanghai Gold Zone:
cn-shanghai-fin-sofastack-middleware-acvip-prod.cloud.alipaycs.netHangzhou Non-Gold Zone:
cn-hangzhou-middleware-acvip-prod.cloud.alipaycs.net
The corresponding key in the
application.propertiesfile iscom.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.propertiesfile iscom.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.propertiesfile iscom.antcloud.mw.secret.
Configure the run mode and environment, as shown in the following example:
run.mode=NORMAL com.alipay.env=sharedConfigure the parameters that you obtained in the previous steps in the
application.propertiesfile.
NoteFor 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-appormyclient-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;NoteIn this example, the
ReferenceHolderclass 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
SOFABootWebSpringApplicationin themyserver-appweb module to publish the service.Start
SOFABootWebSpringApplicationin themyclient-appweb module to reference the service.
Validating the sample project service
Start
SOFABootWebSpringApplicationin themyserver-appweb module to publish the service.Start
SOFABootWebSpringApplicationin themyclient-appweb module to reference the service.After the service is successfully referenced, the
myclient-appconsole displays the following output:Response from myserver-app.rest:HelloSOFARest! times = xxAccess
http://localhost:8341/sofarest/helloin 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
Package the local application.
For more information about the procedure, see Run locally.
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:
For classic application services, see Quick Start.
For containerized application services, see Quick Start.
Service management
On the Service Management page, you can query and manage the published RPC services. For more information, see View services.