Http 协议基本使用

在 SOFARPC (非SOFABoot 环境)中,当使用Http作为服务端协议的时候,支持Json作为序列化方式,作为一些基础的测试方式使用。

SOFARPC API 使用

发布服务

  1. // 只有1个线程 执行
  2. ServerConfig serverConfig = new ServerConfig()
  3. .setStopTimeout(60000)
  4. .setPort(12300)
  5. .setProtocol(RpcConstants.PROTOCOL_TYPE_HTTP)
  6. .setDaemon(true);
  7. // 发布一个服务,每个请求要执行1秒
  8. ProviderConfig<HttpService> providerConfig = new ProviderConfig<HttpService>()
  9. .setInterfaceId(HttpService.class.getName())
  10. .setRef(new HttpServiceImpl())
  11. .setApplication(new ApplicationConfig().setAppName("serverApp"))
  12. .setServer(serverConfig)
  13. .setUniqueId("uuu")
  14. .setRegister(false);
  15. providerConfig.export();

服务引用

因为是Http+Json,所以引用方可以直接通过HttpClient进行调用,以下为一段测试代码。

  1. private ObjectMapper mapper = new ObjectMapper();
  2. HttpClient httpclient = HttpClientBuilder.create().build();
  3. // POST 正常请求
  4. String url = "http://127.0.0.1:12300/com.alipay.sofa.rpc.server.http.HttpService:uuu/object";
  5. HttpPost httpPost = new HttpPost(url);
  6. httpPost.setHeader(RemotingConstants.HEAD_SERIALIZE_TYPE, "json");
  7. ExampleObj obj = new ExampleObj();
  8. obj.setId(1);
  9. obj.setName("xxx");
  10. byte[] bytes = mapper.writeValueAsBytes(obj);
  11. ByteArrayEntity entity = new ByteArrayEntity(bytes,
  12. ContentType.create("application/json"));
  13. httpPost.setEntity(entity);
  14. HttpResponse httpResponse = httpclient.execute(httpPost);
  15. Assert.assertEquals(200, httpResponse.getStatusLine().getStatusCode());
  16. byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());
  17. ExampleObj result = mapper.readValue(data, ExampleObj.class);
  18. Assert.assertEquals("xxxxx", result.getName());