前言:上周使用motan是通过group远程调用超级土豆的服务,但是因为我需要写一些服务,不得不在本地启动服务,于是就详细的自己配置了一次motan。
上一篇博客也说到了,motan主要有3部分组成:registry,server和client。其中我们的registry用的是consul。下面就这3个部分一个一个的说明:
1、pom.xml 添加motan依赖:
一般来说,在公共模块的pom文件里添加依赖就可以了,比如在server、client、dao和common的SNA编程模型下,只要在common的pom文件中添加依赖即可
1 <dependency> 2 <groupId>com.weibo</groupId> 3 <artifactId>motan-core</artifactId> 4 <version>RELEASE</version> 5 </dependency> 6 <dependency> 7 <groupId>com.weibo</groupId> 8 <artifactId>motan-transport-netty</artifactId> 9 <version>RELEASE</version> 10 </dependency> 11 12 <!-- only needed for spring-based features --> 13 <dependency> 14 <groupId>com.weibo</groupId> 15 <artifactId>motan-springsupport</artifactId> 16 <version>RELEASE</version> 17 </dependency> 18 <dependency> 19 <groupId>org.springframework</groupId> 20 <artifactId>spring-context</artifactId> 21 <version>4.2.4.RELEASE</version> 22 </dependency>
2、配置motan
Motan框架中将功能模块抽象为四个可配置的元素,分别为:
-
protocol:服务通信协议。服务提供方与消费方进行远程调用的协议,默认为Motan协议,使用hessian2进行序列化,netty作为Endpoint以及使用Motan自定义的协议编码方式。
-
registry:注册中心。服务提供方将服务信息(包含ip、端口、服务策略等信息)注册到注册中心,服务消费方通过注册中心发现服务。当服务发生变更,注册中心负责通知各个消费方。
-
service:服务提供方提供的服务。使用方将核心业务抽取出来,作为独立的服务。通过暴露服务并将服务注册至注册中心,从而使调用方调用。
-
referer:服务消费方对服务的引用,即服务调用方。
一般来说,在server端需要配置registry、protocol和service;在client端需要配置registry、protocol和referer。
Motan推荐使用spring配置rpc服务,目前Motan扩展了6个自定义Spring xml标签:
- motan:protocol
- motan:registry
- motan:basicService
- motan:service
- motan:basicReferer
- motan:referer
详细配置:
<motan:registry/>
注册中心配置。用于配置注册中心的注册协议、地址端口、超时时间等。motan:registry包含以下常用属性:
-
- name:标识配置名称
- regProtocol:标识注册中心协议
- address:标识注册中心地址
Motan支持使用多种Registry模块,使用不同注册中心需要依赖对应jar包。
以consul为注册中心举例:
<motan:registry regProtocol="consul"
name="my_consul"
address="${my.consul.address}"/>
下表是registry的所有属性说明:
Property name | Type | Default | Comment |
---|---|---|---|
name | String | 注册配置名称 | |
regProtocol | String | 注册协议 | |
address | String | 注册中心地址 | |
port | int | 0 | 注册中心缺省端口 |
connectTimeout | int | 1000 | 注册中心连接超时时间(毫秒) |
requestTimeout | int | 200 | 注册中心请求超时时间(毫秒) |
registrySessionTimeout | int | 60s | 注册中心会话超时时间(毫秒) |
registryRetryPeriod | int | 30s | 失败后重试的时间间隔 |
check | boolean | true | 启动时检查失败后是否仍然启动 |
register | boolean | true | 在该注册中心上服务是否暴露 |
subscribe | boolean | true | 在该注册中心上服务是否引用 |
default | boolean | 是否缺省的配置 |
<motan:service/> 和 <motan:basicService/>
protocol、basic service、extConfig、service中定义相同属性时,优先级为service > extConfig > basic service > protocol
<motan:service .../>
motan:service包含以下常用属性:
-
- interface:标识服务的接口类名
- ref:标识服务的实现类,引用具体的spring业务实现对象
- export:标识服务的暴露方式,格式为“protocolId:port”(使用的协议及对外提供的端口号),其中protocolId:应与motan:protocol中的id一致
- group:标识服务的分组
- module:标识模块信息
- basicService:标识使用的基本配置,引用motan:basicService对象