栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

motan快速入门

motan快速入门

由于github时不时的无法访问,所以把官网的信息黏贴过来。

简单调用示例 同步调用
  1. 在pom中添加依赖

     
         com.weibo
         motan-core
         RELEASE
     
     
         com.weibo
         motan-transport-netty
         RELEASE
     
     
     
     
         com.weibo
         motan-springsupport
         RELEASE
     
     
         org.springframework
         spring-context
         4.2.4.RELEASE
     
  2. 为调用方和服务方创建公共接口。

    src/main/java/quickstart/FooService.java

    package quickstart;
    
    public interface FooService {
        public String hello(String name);
    }
  3. 编写业务接口逻辑、创建并启动RPC Server。

    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;
        }
    }

    src/main/resources/motan_server.xml

    
    
    
        
        
        
        
    
    `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...");
        }
    }

    执行Server类中的main函数将会启动Motan服务,并监听8002端口.

  4. 创建并执行RPC Client。

    src/main/resources/motan_client.xml

    
    
    
        
        
    

    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"));
        }
    }

    执行Client类中的main函数将执行一次远程调用,并输出结果。

异步调用

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

  1. 在接口类上加@MotanAsync注解

    package quickstart;
    
    @MotanAsync
    public interface FooService {
        public String hello(String name);
    }
  2. 编译时,Motan自动生成异步service类,生成路径为target/generated-sources/annotations/,生成的类名为service名加上Async,例如service类名为FooService.java,则自动生成的类名为FooServiceAsync.java。 另外,需要将motan自动生产类文件的路径配置为项目source path,可以使用maven plugin或手动配置。pom.xml配置如下:

    
        org.codehaus.mojo
        build-helper-maven-plugin
        RELEASE
        
            
                generate-sources
                
                    add-source
                
                
                    
                        ${project.build.directory}/generated-sources/annotations
                    
                
            
        
    
  3. 在client端配置motan_client.xml时,在同步调用配置的基础上,只需要修改referer的interface为Motan自动生成的接口类即可。

  4. 异步使用方式如下:

    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依赖

    
        com.weibo
        motan-registry-consul
        RELEASE
    
  2. 在server和client的配置文件中分别增加consul registry定义。

  3. 在Motan client及server配置改为通过registry服务发现。

    client

        

    server

        
  4. server程序启动后,需要显式调用心跳开关,注册到consul。

    MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true)
  5. 进入ui后台查看服务是否正常提供调用

  6. 启动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依赖

    
        com.weibo
        motan-registry-zookeeper
        RELEASE
    
  2. 在server和client的配置文件中分别增加zookeeper registry定义。

    zookeeper为单节点

    zookeeper多节点集群

  3. 在Motan client及server配置改为通过registry服务发现。

    client

    server

  4. server程序启动后,需要显式调用心跳开关,注册到zookeeper。

    MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true)
  5. 启动client,调用服务

其他调用示例 提供YAR协议服务

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

 
     com.weibo
     motan-protocol-yar
     RELEASE
 

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

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

3、配置protocol的name="yar"

 

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

 

具体配置见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包

 
     com.weibo
     motan-protocol-restful
     RELEASE
 

接口声明与实现

服务接口

 @Path("/rest")
 public interface RestfulService {
     @GET
     @Produces(MediaType.APPLICATION_JSON)
     List 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 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端配置:

     
 
     
 
     
 
     
 
     

client端配置:

     
 
     
     
 
     
     
 
     
     

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

此时需要注意contextpath问题

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

 
 
     com.weibo.api.motan.protocol.restful.support.servlet.RestfulServletContainerListener
 

 
     dispatcher
     org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
     1
     
         resteasy.servlet.mapping.prefix
         /servlet  
     
 

 
     dispatcher
     /servlet/*
 

集成到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扩展

 
     com.weibo
     filter-opentracing
     RELEASE
 

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版本为1.0.0以上
  • 使用motan2协议
  • 序列化方式必须通信的两种语言同时支持

Motan支持与其他语言版本进行交互,跨语言调用时,需要使用motan2协议,并且需要使用能够进行跨语言交互的序列化方式。由于不同语言特点的不同,跨语言交互时需要在接口设计上进行tradeoff,尽量使用简单数据结构作为参数与返回值。一般以参数和返回值能够进行跨语言序列化与反序列化即可。

Motan2协议可以支持不同序列化方式,序列化方式在不同语言实现中都为可扩展点,如果需要使用定制化的序列化方式,需要交互的语言同时拥有该序列化实现。目前Motan-go版本支持simple序列化,一般接口建议使用此序列化方式,其他序列化方式在后续版本中也会逐步提供。

一般在各版本的demo中使用的都是相同的服务声明,可以进行跨语言调用,后续会在单独的项目中提供各个语言的调用demo,请关注wiki的更新。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/335788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号