编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

微博轻量级 RPC 框架 Motan(微博xposed模块)

wxchong 2024-08-18 00:38:50 开源技术 11 ℃ 0 评论

概述

Motan 是一套高性能、易于使用的分布式远程服务调用(RPC)框架。

功能

  • 支持通过spring配置方式集成,无需额外编写代码即可为服务提供分布式调用能力。
  • 支持集成consul、zookeeper等配置服务组件,提供集群环境的服务发现及治理能力。
  • 支持动态自定义负载均衡、跨机房流量调整等高级服务调度能力。
  • 基于高并发、高负载场景进行优化,保障生产环境下RPC服务高可用。

简单调用示例

同步调用

  1. 在pom中添加依赖
 <dependency>
 <groupId>com.weibo</groupId>
 <artifactId>motan-core</artifactId>
 <version>RELEASE</version>
 </dependency>
 <dependency>
 <groupId>com.weibo</groupId>
 <artifactId>motan-transport-netty</artifactId>
 <version>RELEASE</version>
 </dependency>
 
 <!-- only needed for spring-based features -->
 <dependency>
 <groupId>com.weibo</groupId>
 <artifactId>motan-springsupport</artifactId>
 <version>RELEASE</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>4.2.4.RELEASE</version>
 </dependency>
  1. 为调用方和服务方创建公共接口。
  2. src/main/java/quickstart/FooService.java
package quickstart;
public interface FooService {
 public String hello(String name);
}
  1. 编写业务接口逻辑、创建并启动RPC Server。
  2. src/main/java/quickstart/FooServiceImpl.java
package quickstart;
public class FooServiceImpl implements FooService {
 public String hello(String name) {
 System.out.println(name + " invoked rpc service");
 return "hello " + name;
 }
}
  1. src/main/resources/motan_server.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:motan="http://api.weibo.com/schema/motan"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://api.weibo.com/schema/motan http://api.weibo.com/schema/motan.xsd">
 <!-- service implemention bean -->
 <bean id="serviceImpl" class="quickstart.FooServiceImpl" />
 <!-- exporting service by Motan -->
 <motan:service interface="quickstart.FooService" ref="serviceImpl" export="8002" />
</beans>
`src/main/java/quickstart/Server.java`
package quickstart;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Server {
 public static void main(String[] args) throws InterruptedException {
 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:motan_server.xml");
 System.out.println("server start...");
 }
}
  1. 执行Server类中的main函数将会启动Motan服务,并监听8002端口.
  2. 创建并执行RPC Client。
  3. src/main/resources/motan_client.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:motan="http://api.weibo.com/schema/motan"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://api.weibo.com/schema/motan http://api.weibo.com/schema/motan.xsd">
 <!-- reference to the remote service -->
 <motan:referer id="remoteService" interface="quickstart.FooService" directUrl="localhost:8002"/>
</beans>
  1. src/main/java/quickstart/Client.java
package quickstart;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
 public static void main(String[] args) throws InterruptedException {
 ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:motan_client.xml");
 FooService service = (FooService) ctx.getBean("remoteService");
 System.out.println(service.hello("motan"));
 }
}
  1. 执行Client类中的main函数将执行一次远程调用,并输出结果。

异步调用

异步调用与同步调用基本配置完全一样,只需要在接口类中加上@MotanAsync注解,然后client端稍作修改。server端不需要做任何修改。具体步骤如下:

  1. 在接口类上加@MotanAsync注解
package quickstart;
@MotanAsync
public interface FooService {
 public String hello(String name);
}
  1. 编译时,Motan自动生成异步service类,生成路径为target/generated-sources/annotations/,生成的类名为service名加上Async,例如service类名为FooService.java,则自动生成的类名为FooServiceAsync.java。 另外,需要将motan自动生产类文件的路径配置为项目source path,可以使用maven plugin或手动配置。pom.xml配置如下:
<plugin>
 <groupId>org.codehaus.mojo</groupId>
 <artifactId>build-helper-maven-plugin</artifactId>
 <version>RELEASE</version>
 <executions>
 <execution>
 <phase>generate-sources</phase>
 <goals>
 <goal>add-source</goal>
 </goals>
 <configuration>
 <sources>
 <source>${project.build.directory}/generated-sources/annotations</source>
 </sources>
 </configuration>
 </execution>
 </executions>
</plugin>
  1. 在client端配置motan_client.xml时,在同步调用配置的基础上,只需要修改referer的interface为Motan自动生成的接口类即可。
<motan:referer id="remoteService" interface="quickstart.FooServiceAsync" directUrl="localhost:8002"/>
  1. 异步使用方式如下:
public static void main(String[] args) {
 ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {"classpath:motan_client.xml"});
 FooServiceAsync service = (FooServiceAsync) ctx.getBean("remoteService");
 // sync call
 System.out.println(service.hello("motan"));
 // async call
 ResponseFuture future = service.helloAsync("motan async ");
 System.out.println(future.getValue());
 // multi call
 ResponseFuture future1 = service.helloAsync("motan async multi-1");
 ResponseFuture future2 = service.helloAsync("motan async multi-2");
 System.out.println(future1.getValue() + ", " + future2.getValue());
 // async with listener
 FutureListener listener = new FutureListener() {
 @Override
 public void operationComplete(Future future) throws Exception {
 System.out.println("async call "
 + (future.isSuccess() ? "sucess! value:" + future.getValue() : "fail! exception:"
 + future.getException().getMessage()));
 }
 };
 ResponseFuture future3 = service.helloAsync("motan async multi-1");
 ResponseFuture future4 = service.helloAsync("motan async multi-2");
 future3.addListener(listener);
 future4.addListener(listener);
}

具体代码可以参考demo模块

集群调用示例

在集群环境下使用Motan需要依赖外部服务发现组件,目前支持consul或zookeeper。

使用Consul作为注册中心

Consul安装与启动

安装(官方文档)

# 这里以linux为例
wget https://releases.hashicorp.com/consul/0.6.4/consul_0.6.4_linux_amd64.zip
unzip consul_0.6.4_linux_amd64.zip
sudo mv consul /bin

启动(官方文档)

测试环境启动:
consul agent -dev

ui后台 http://localhost:8500/ui

Motan-Consul配置

  1. 在server和client中添加motan-registry-consul依赖
<dependency>
 <groupId>com.weibo</groupId>
 <artifactId>motan-registry-consul</artifactId>
 <version>RELEASE</version>
</dependency>
  1. 在server和client的配置文件中分别增加consul registry定义。
<motan:registry regProtocol="consul" name="my_consul" address="127.0.0.1:8500"/>
  1. 在Motan client及server配置改为通过registry服务发现。
  2. client
 <motan:referer id="remoteService" interface="quickstart.FooService" registry="my_consul"/>
  1. server
 <motan:service interface="quickstart.FooService" ref="serviceImpl" registry="my_consul" export="8002" />
  1. server程序启动后,需要显式调用心跳开关,注册到consul。
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true)
  1. 进入ui后台查看服务是否正常提供调用
  2. 启动client,调用服务

使用ZooKeeper作为注册中心

ZooKeeper安装与启动(官方文档)

单机版安装与启动

wget http://mirrors.cnnic.cn/apache/zookeeper/zookeeper-3.4.8/zookeeper-3.4.8.tar.gz
tar zxvf zookeeper-3.4.8.tar.gz
cd zookeeper-3.4.8/conf/
cp zoo_sample.cfg zoo.cfg
cd ../
sh bin/zkServer.sh start

Motan-ZooKeeper配置

  1. 在server和client中添加motan-registry-zookeeper依赖
<dependency>
 <groupId>com.weibo</groupId>
 <artifactId>motan-registry-zookeeper</artifactId>
 <version>RELEASE</version>
</dependency>
  1. 在server和client的配置文件中分别增加zookeeper registry定义。
  2. zookeeper为单节点
<motan:registry regProtocol="zookeeper" name="my_zookeeper" address="127.0.0.1:2181"/>
  1. zookeeper多节点集群
<motan:registry regProtocol="zookeeper" name="my_zookeeper" address="127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183"/>
  1. 在Motan client及server配置改为通过registry服务发现。
  2. client
<motan:referer id="remoteService" interface="quickstart.FooService" registry="my_zookeeper"/>
  1. server
<motan:service interface="quickstart.FooService" ref="serviceImpl" registry="my_zookeeper" export="8002" />
  1. server程序启动后,需要显式调用心跳开关,注册到zookeeper。
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true)
  1. 启动client,调用服务

其他调用示例

提供YAR协议服务

YAR协议是php的一个rpc扩展,motan框架可以提供yar协议的RPC服务 1、引入motan-protocol-yar.jar

 <dependency>
 <groupId>com.weibo</groupId>
 <artifactId>motan-protocol-yar</artifactId>
 <version>RELEASE</version>
 </dependency>

2、在服务接口类上增加注解@YarConfig,声明服务的uri

 @YarConfig(path = "/openapi/yarserver/test")
 public interface YarService {
 public String hello(String name);
 }

3、配置protocol的name="yar"

 <motan:protocol id="demoYar" name="yar" .../>

4、配置service的export,使用yar协议提供服务

 <motan:service interface="com.weibo.motan.demo.service.YarService"
 export="demoYar:8003" .../>

具体配置见motan-demo模块 YAR协议使用yar-java进行解析,java作为YAR client时可以直接使用

使用注解方式配置motan

server端配置

1、声明Annotation用来指定需要解析的包名

 @Bean
 public AnnotationBean motanAnnotationBean() {
 AnnotationBean motanAnnotationBean = new AnnotationBean();
 motanAnnotationBean.setPackage("com.weibo.motan.demo.server");
 return motanAnnotationBean;
 }

2、配置ProtocolConfig、RegistryConfig、BasicServiceConfig的bean对象,功能与xml配置中的protocol、registry、basicService标签一致。

 @Bean(name = "demoMotan")
 public ProtocolConfigBean protocolConfig1() {
 ProtocolConfigBean config = new ProtocolConfigBean();
 config.setDefault(true);
 config.setName("motan");
 config.setMaxContentLength(1048576);
 return config;
 }
 @Bean(name = "registryConfig1")
 public RegistryConfigBean registryConfig() {
 RegistryConfigBean config = new RegistryConfigBean();
 config.setRegProtocol("local");
 return config;
 }
 @Bean
 public BasicServiceConfigBean baseServiceConfig() {
 BasicServiceConfigBean config = new BasicServiceConfigBean();
 config.setExport("demoMotan:8002");
 config.setGroup("testgroup");
 config.setAccessLog(false);
 config.setShareChannel(true);
 config.setModule("motan-demo-rpc");
 config.setApplication("myMotanDemo");
 config.setRegistry("registryConfig1");
 return config;
 }

3、service的实现类上添加@MotanService注解,注解的配置参数与xml配置方式的service标签一致。

 @MotanService(export = "demoMotan:8002")
 public class MotanDemoServiceImpl implements MotanDemoService {
 public String hello(String name) {
 System.out.println(name);
 return "Hello " + name + "!";
 }
 }

4、使用spring-boot启动服务

 @EnableAutoConfiguration
 @SpringBootApplication
 public class SpringBootRpcServerDemo {
 public static void main(String[] args) {
 System.setProperty("server.port", "8081");
 ConfigurableApplicationContext context = SpringApplication.run(SpringBootRpcServerDemo.class, args);
 
 MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
 System.out.println("server start...");
 }
 }

server端详细配置请参考motan-demo模块

client端配置

1、声明Annotation、protocolConfig、RegistryConfig的配置bean。方式与server端配置类似。

2、配置basicRefererConfig bean

 @Bean(name = "motantestClientBasicConfig")
 public BasicRefererConfigBean baseRefererConfig() {
 BasicRefererConfigBean config = new BasicRefererConfigBean();
 config.setProtocol("demoMotan");
 config.setGroup("motan-demo-rpc");
 config.setModule("motan-demo-rpc");
 config.setApplication("myMotanDemo");
 config.setRegistry("registry");
 config.setCheck(false);
 config.setAccessLog(true);
 config.setRetries(2);
 config.setThrowException(true);
 return config;
 }

3、在使用motan service 的对象上添加@MotanReferer注解,注册配置与xml方式的referer标签一致

 @RestController
 public class HelloController {
 @MotanReferer(basicReferer = "motantestClientBasicConfig", group = "testgroup", directUrl = "127.0.0.1:8002")
 MotanDemoService service;
 @RequestMapping("/")
 @ResponseBody
 public String home() {
 String result = service.hello("test");
 return result;
 }
 }

4、使用spring-boot启动client

 @EnableAutoConfiguration
 @SpringBootApplication
 public class SpringBootRpcClientDemo {
 public static void main(String[] args) {
 SpringApplication.run(SpringBootRpcClientDemo.class, args);
 }
 }

client端详细配置请参考motan-demo模块

使用restful协议

功能支持

  1. 支持rpc单独进程和部署到servlet容器中
  2. 完全支持原有服务治理功能
  3. 支持rpc request/response的attachment机制
  4. 完全支持rpc filter机制
  5. rest服务编程完全按照JAX-RS代码方式编写

前置条件

引入motan-protocol-restful包

 <dependency>
 <groupId>com.weibo</groupId>
 <artifactId>motan-protocol-restful</artifactId>
 <version>RELEASE</version>
 </dependency>

接口声明与实现

服务接口

 @Path("/rest")
 public interface RestfulService {
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 List<User> getUsers(@QueryParam("uid") int uid);
 
 @GET
 @Path("/primitive")
 @Produces(MediaType.TEXT_PLAIN)
 String testPrimitiveType();
 
 @POST
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 @Produces(MediaType.APPLICATION_JSON)
 Response add(@FormParam("id") int id, @FormParam("name") String name);
 
 @GET
 @Path("/exception")
 @Produces(MediaType.APPLICATION_JSON)
 void testException();
 }

服务实现

 public class RestfulServerDemo implements RestfulService {
 
 @Override
 public List<User> getUsers(@CookieParam("uid") int uid) {
 return Arrays.asList(new User(uid, "name" + uid));
 }
 
 @Override
 public String testPrimitiveType() {
 return "helloworld!";
 }
 
 @Override
 public Response add(@FormParam("id") int id, @FormParam("name") String name) {
 return Response.ok().cookie(new NewCookie("ck", String.valueOf(id))).entity(new User(id, name)).build();
 }
 
 @Override
 public void testException() {
 throw new UnsupportedOperationException("unsupport");
 }
 }

配置restserver

独立rpc进程方式

server端配置:

 <bean id="motanDemoServiceImpl" class="com.weibo.motan.demo.server.RestfulServerDemo"/>
 
 <motan:registry regProtocol="local" name="registry" />
 
 <motan:protocol id="demoRest" name="restful" endpointFactory="netty"/>
 
 <motan:basicService export="demoRest:8004" group="motan-demo-rpc" module="motan-demo-rpc"
 application="myMotanDemo" registry="registry" id="serviceBasicConfig"/>
 
 <motan:service interface="com.weibo.motan.demo.service.RestfulService"
 ref="motanDemoServiceImpl" basicService="serviceBasicConfig"/>

client端配置:

 <motan:registry regProtocol="direct" name="registry" address="127.0.0.1:8004"/>
 
 <!-- restful 协议 -->
 <motan:protocol id="restfulProtocol" name="restful" endpointFactory="netty"/>
 
 <!-- 通用referer基础配置 -->
 <motan:basicReferer requestTimeout="1000" group="motan-demo-rpc" module="motan-demo-rpc"
 application="myMotanDemo" protocol="restfulProtocol" registry="registry"
 id="motanTestClientBasicConfig" />
 
 <!-- 使用 restful 协议-->
 <motan:referer id="restfulReferer" interface="com.weibo.motan.demo.service.RestfulService"
 basicReferer="motanTestClientBasicConfig"/>

集成到java应用服务器中(如部署到tomcat中)

此时需要注意contextpath问题

<motan:protocol name="restful" endpointFactory="servlet" />

服务端还需配置web.xml如下:

 <!-- 此filter必须在spring ContextLoaderFilter之前 -->
 <listener>
 <listener-class>com.weibo.api.motan.protocol.restful.support.servlet.RestfulServletContainerListener</listener-class>
 </listener>
 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
 <load-on-startup>1</load-on-startup>
 <init-param>
 <param-name>resteasy.servlet.mapping.prefix</param-name>
 <param-value>/servlet</param-value> <!-- 此处实际为servlet-mapping的url-pattern,具体配置见resteasy文档-->
 </init-param>
 </servlet>
 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/servlet/*</url-pattern>
 </servlet-mapping>

集成到java应用服务器的方式(servlet方式)适合不同语言直接http调用,需要注意url中contextpath的问题。推荐使用rpc进程方式

java作为client端调用时,推荐server端同时导出restful和motan两种协议,java使用motan协议进行调用,其他语言使用标准http协议调用。

详细请参考motan-demo模块中的RestfulServerDemo、RestfulClient

使用OpenTracing

Motan通过filter的SPI扩展机制支持OpenTracing,可以支持任何实现了OpenTracing标准的trace实现。使用OpenTracing需要以下步骤。

1、引入filter-opentracing扩展

 <dependency>
 <groupId>com.weibo</groupId>
 <artifactId>filter-opentracing</artifactId>
 <version>RELEASE</version>
 </dependency>

2、如果第三方trace工具声明了io.opentracing.Tracer的SPI扩展,直接引入第三方trace的jar包即可。如果第三方没有声明,则转第三步。

3、自定义一个TracerFactory实现TracerFactory接口,通过getTracer()来获取不同tracer实现。设置OpenTracingContext的tracerFactory为自定义的TracerFactory即可。

可参考filter-opentracing模块src/test/java/com.weibo.api.motan.filter.opentracing.zipkin.demo包下的server端和client端实现。

优雅的停止服务

Motan支持在Consul、ZooKeeper集群环境下优雅的关闭节点,当需要关闭或重启节点时,可以先将待上线节点从集群中摘除,避免直接关闭影响正常请求。

待关闭节点需要调用以下代码,建议通过servlet或业务的管理模块进行该调用。

MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, false)

管理后台

管理后台主要包括RPC服务查询、流量切换、Motan指令设置等功能,需使用ZooKeeper作为注册中心

管理后台独立于Motan其他部分,可单独部署

管理后台安装

  1. 配置
  2. 修改配置文件application.properties,配置注册中心类型(zookeeper, consul)及注册中心地址,默认不使用数据库
  3. 默认的登录用户及权限如下:
 管理员:用户名admin 密码admin
 访客:用户名guest 密码guest
  1. 若需使用历史操作查询功能,则需配置数据库:
  • 数据库表结构位于motan-manager.sql,可直接导入
  • 数据库配置地址位于application.properties
  • 修改 MotanManagerApp 注解 @ImportResource(locations = {"classpath:spring-security.xml"})为 +@ImportResource(locations = {"classpath:spring-mybatis.xml", "classpath:spring-security.xml"})
  1. 启动
  2. 在 motan/motan-manager/ 下执行 mvn package, 然后 java -jar target/motan-manager.jar 。

管理后台使用

RPC服务查询

查询指定group的所有service状态,包括正常提供服务的Server和正在调用的Client

注:Consul注册中心暂不支持Client查询

步骤:

  • 在导航栏选择RPC服务查询,进入RPC服务查询页面
  • 下拉列表中选择要查询的服务所在的分组,如motan-demo-rpc,点击查询按钮

流量切换(需要管理员权限)

对指定服务根据分组或ip地址进行动态流量调整

步骤:

以下示例演示将来自motan-demo-rpc分组中所有服务的流量切换到motan-demo-rpc2分组中

  • 在导航栏选择流量切换,进入流量切换页面
  • Step1:
  • 来源流量的RPC分组列表中选择需要切换流量的Service所在的分组,如motan-demo-rpc
  • 服务列表中*表示所有服务,也可输入服务名称,语法见服务名语法,点击Next

  • Step2:
  • 目标流量的RPC分组列表中选择目标流量分组,如motan-demo-rpc2,
  • 流量权重分配中根据需要按比例分配(可选范围是[0,100]),这里输入0和1,表示将来自motan-demo-rpc的流量全部转入motan-demo-rpc2,点击Next

  • Step3:(可选)若需根据具体IP调整流量,可在此配置
  • RPC Client中输入来源流量的ip,RPC Server中输入目标流量的ip,点击添加后将在路由规则结果中显示
  • 也可在路由规则结果中手动输入路由规则,路由规则见路由规则语法,点击Next

  • Step4:指令预览
  • 功能暂未启用,点击Finish完成流量切换操作

服务名语法

  • 类名支持[a-zA-Z0-9_$.*]
  • 运算符支持 () ! & |,优先级由高到低
  • 复杂示例如下
(com.weibo.User* & !com.weibo.UserMapping) | com.weibo.Status*
# 匹配com.weibo下以User开头的不包括UserMapping的所有服务,或以Status开头的所有服务

路由规则语法

  • 必须包含to关键字,to左右两边分别为rpc client和rpc server的ip表达式,示例如下
* to 10.75.1.*
10.75.2.* to 10.73.1.*
* to !10.75.1.1

指令管理

对注册中心下的所有指令信息进行增删改查操作

步骤:

  • 在导航栏选择指令查询,进入指令查询页面
  • 指令修改和删除操作需要管理员权限

操作记录查询(需要管理员权限)

查询指令增删改查记录

步骤:

  • 在导航栏选择操作记录查询,进入操作记录查询

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表