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.
<dependency>
<groupId>com.alipay.sofa</groupId>
<artifactId>rpc-enterprise-sofa-boot-starter</artifactId>
</dependency>
Publish a service
Service interface definition
@Path("/webapi")
@Consumes("application/json;charset=UTF-8")
@Produces("application/json;charset=UTF-8")
public interface RestService {
@GET
@Path("/restService/{id}")
String sayRest(@PathParam("id") String string);
}
Service implementation
public class RestServiceImpl implements RestService {
@Override
public String sayRest(String string) {
return "rest";
}
}
XML configuration
Add service publication configuration in rpc_server.xml
:
<bean id="restServiceImpl" class="com.alipay.sofa.rpc.samples.rest.RestServiceImpl"/>
<sofa:service ref="restServiceImpl" interface="com.alipay.sofa.rpc.samples.rest.RestService">
<sofa:binding.rest/>
</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
:
<sofa:reference id="restServiceReference" interface="com.alipay.sofa.rpc.samples.rest.RestService">
<sofa:binding.rest/>
</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:
RestService restService = (RestService) applicationContext.getBean("restServiceReference");
String result = restService.sayRest("rest");
You can also initiate a service invocation request by using HttpClient or a browser:
# curl http://127.0.0.1:8341/webapi/restService/1
rest%