All Products
Search
Document Center

SOFAREST Quick Start

Last Updated: Aug 17, 2020

SOFARPC supports the REST protocol, DSR (Direct Server Return), and SLB (Server Load Balancer).

Prerequisites

Import the following dependency in the project. The version is controlled by SOFABoot.

  1. <dependency>
  2. <groupId>com.alipay.sofa</groupId>
  3. <artifactId>rpc-enterprise-sofa-boot-starter</artifactId>
  4. </dependency>

Publish a service

Service interface definition

  1. @Path("/webapi")
  2. @Consumes("application/json;charset=UTF-8")
  3. @Produces("application/json;charset=UTF-8")
  4. public interface RestService {
  5. @GET
  6. @Path("/restService/{id}")
  7. String sayRest(@PathParam("id") String string);
  8. }

Service implementation

  1. public class RestServiceImpl implements RestService {
  2. @Override
  3. public String sayRest(String string) {
  4. return "rest";
  5. }
  6. }

XML configuration

Add service publication configuration in rpc_server.xml:

  1. <bean id="restServiceImpl" class="com.alipay.sofa.rpc.samples.rest.RestServiceImpl"/>
  2. <sofa:service ref="restServiceImpl" interface="com.alipay.sofa.rpc.samples.rest.RestService">
  3. <sofa:binding.rest/>
  4. </sofa:service>

The default port for publishing services is Port 8341. You can change the default port of SOFAREST by configuring com.alipay.sofa.rpc.rest.port. For more information, see RPC app parameter configuration and SOFABoot system configuration parameters.

Reference the service

Add service reference configuration in rpc_client.xml:

  1. <sofa:reference id="restServiceReference" interface="com.alipay.sofa.rpc.samples.rest.RestService">
  2. <sofa:binding.rest/>
  3. </sofa:reference>

Service Invocation

SOFARPC supports direct invocation of RESTful services. In an invocation, the SLB address is obtained from the SOFARegistry. The following shows the example code:

  1. RestService restService = (RestService) applicationContext.getBean("restServiceReference");
  2. String result = restService.sayRest("rest");

You can also initiate a service invocation request by using HttpClient or a browser:

  1. # curl http://127.0.0.1:8341/webapi/restService/1
  2. rest%