用透明RPC开发微服务

概念阐述

透明RPC开发模式是一种基于接口和接口实现的开发模式,服务的开发者不需要使用Spring MVC和JAX-RS注解。

开发示例

透明RPC开发模式支持Spring xml配置和注解配置两种服务发布方式,通过Spring xml配置的方式如下:

步骤 1定义服务接口。

根据开发之前定义好的契约,编写Java业务接口,代码如下:

  1. public interface Hello {
  2. String sayHi(String name);
  3. String sayHello(Person person);
  4. }
  5. public interface Compute {
  6. int add(int a, int b);
  7. int multi(int a, int b);
  8. int sub(int a, int b);
  9. int divide(int a, int b);
  10. }

步骤 2实现服务

Hello的服务实现如下:

说明:每一个服务接口都需要定义一个schema声明。
  • 在接口Hello 和 Compute 的实现类上使用@RpcSchema注解定义schema,代码如下:
  1. @RpcSchema(schemaId = "hello")
  2. public class HelloImpl implements Hello {
  3. @Override
  4. public String sayHi(String name) {
  5. return "Hello " + name;
  6. }
  7. @Override
  8. public String sayHello(Person person) {
  9. return "Hello person " + person.getName();
  10. }
  11. }
  12. @RpcSchema(schemaId = "codeFirstCompute")
  13. public class CodeFirstComputeImpl implements Compute {
  14. @Override
  15. public int add(int a, int b) {
  16. return a + b;
  17. }
  18. @Override
  19. public int multi(int a, int b) {
  20. return a * b;
  21. }
  22. @Override
  23. public int sub(int a, int b) {
  24. return a - b;
  25. }
  26. @Override
  27. public int divide(int a, int b) {
  28. if (b != 0) {
  29. return a / b;
  30. }
  31. return 0;
  32. }
  33. }

步骤 3发布服务

  • 通过配置文件方式
    在resources/META-INF/spring目录下的pojoHello.bean.xml文件中,配置Spring进行服务扫描的base-package,文件内容如下:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns=" http://www.springframework.org/schema/beans " xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "
  3. xmlns:p=" http://www.springframework.org/schema/p " xmlns:util=" http://www.springframework.org/schema/util "
  4. xmlns:cse=" http://www.huawei.com/schema/paas/cse/rpc "
  5. xmlns:context=" http://www.springframework.org/schema/context "
  6. xsi:schemaLocation=" http://www.springframework.org/schema/beans classpath:org/springframework/beans/factory/xml/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.huawei.com/schema/paas/cse/rpc classpath:META-INF/spring/spring-paas-cse-rpc.xsd">
  7. <context:component-scan base-package="org.apache.servicecomb.samples.pojo.provider"/>
  8. </beans>

步骤 4 启动服务

  1. public class PojoProviderMain {
  2. public static void main(String[] args) throws Exception {
  3. Log4jUtils.init();
  4. BeanUtils.init();
  5. }
  6. }
说明:与Spring MVC开发模式和JAX-RS开发模式不同的是,透明RPC开发模式使用的注解是@RpcSchema而非@RestSchema