[RPC] Motan快速开始

文章目录

  • 一、概述
  • 二、功能
  • 三、XML配置使用
    • 1、同步调用
      • 1.1、pom中添加依赖
      • 1.2、为调用方和服务方创建公共接口。
      • 1.3、编写业务接口逻辑、创建并启动RPC Server。
      • 1.4、创建并执行RPC Client。
    • 2、异步调用
      • 2.1、在接口类上加@MotanAsync注解
      • 2.2、在client端配置motan_client.xml时,在同步调用配置的基础上,只需要修改referer的interface为Motan自动生成的接口类即可。
    • 3、Zookeeper注册中心配置
      • 3.1 在server和client中 添加maven依赖
      • 3.2 在server和client 的配置文件中分别增加zookeeper registry定义
      • 3.3 在Motan client及server配置改为通过registry服务发现。
      • 3.4 server程序启动后,需要显式调用心跳开关,注册到zookeeper。
      • 3.5 启动client,调用服务
  • 四、注解配置使用
    • server端配置
      • 1、声明Annotation用来指定需要解析的包名
      • 2、配置ProtocolConfig、RegistryConfig、BasicServiceConfig的bean对象
      • 3、service的实现类上添加@MotanService注解,注解的配置参数与xml配置方式的service标签一致。
      • 4、使用spring-boot启动服务
    • client端配置
      • 1、声明Annotation、protocolConfig、RegistryConfig的配置bean。
      • 2、配置basicRefererConfig bean
      • 3、在使用motan service 的对象上添加@MotanReferer注解,
      • 4、使用spring-boot启动client

一、概述

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

二、功能

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

三、XML配置使用

1、同步调用

1.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、为调用方和服务方创建公共接口。

package quickstart;

public interface FooService {
    public String hello(String name);
}

1.3、编写业务接口逻辑、创建并启动RPC Server。

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

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

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

1.4、创建并执行RPC Client。

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>

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

2、异步调用

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

2.1、在接口类上加@MotanAsync注解

package quickstart;

@MotanAsync
public interface FooService {
    public String hello(String name);
}

编译时,
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>

2.2、在client端配置motan_client.xml时,在同步调用配置的基础上,只需要修改referer的interface为Motan自动生成的接口类即可。

<motan:referer id="remoteService" interface="quickstart.FooServiceAsync" directUrl="localhost:8002"/>

异步使用方式如下:

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

3、Zookeeper注册中心配置

3.1 在server和client中 添加maven依赖

<dependency>
    <groupId>com.weibo</groupId>
    <artifactId>motan-registry-zookeeper</artifactId>
    <version>RELEASE</version>
</dependency>

3.2 在server和client 的配置文件中分别增加zookeeper registry定义

<motan:registry regProtocol="zk" name="my_zookeeper" address="127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183"/>

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

client

<motan:referer id="remoteService" interface="quickstart.FooService" registry="my_zookeeper"/>

server

<motan:service interface="quickstart.FooService" ref="serviceImpl" registry="my_zookeeper" export="8002" />

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

MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true)

3.5 启动client,调用服务


四、注解配置使用

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

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

官网文档

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/105279.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

图论06-【无权无向】-图的遍历并查集Union Find-力扣695为例

文章目录 1. 代码仓库2. 思路2.1 UF变量设计2.2 UF合并两个集合2.3 查找当前顶点的父节点 find(element) 3. 完整代码 1. 代码仓库 https://github.com/Chufeng-Jiang/Graph-Theory 2. 思路 2.1 UF变量设计 parent数组保存着每个节点所指向的父节点的索引&#xff0c;初始值为…

改善游戏体验:数据分析与可视化的威力

当今&#xff0c;电子游戏已经超越了娱乐&#xff0c;成为一种文化现象&#xff0c;汇聚了全球数十亿的玩家。游戏制作公司正采用越来越复杂的技术来提高游戏质量&#xff0c;同时游戏数据分析和可视化工具变得不可或缺。 数据的力量&#xff1a;解析游戏体验 游戏制作涉及到大…

BadNets:基于数据投毒的模型后门攻击代码(Pytorch)以MNIST为例

加载数据集 # 载入MNIST训练集和测试集 transform transforms.Compose([transforms.ToTensor(),]) train_loader datasets.MNIST(rootdata,transformtransform,trainTrue,downloadTrue) test_loader datasets.MNIST(rootdata,transformtransform,trainFalse) # 可视化样本 …

关于本地项目上传到gitee的详细流程

如何上传本地项目到Gitee的流程&#xff1a; 1.Gitee创建项目 2. 进入所在文件夹&#xff0c;右键点击Git Bash Here 3.配置用户名和邮箱 在gitee的官网找到命令&#xff0c;注意这里的用户名和邮箱一定要和你本地的Git相匹配&#xff0c;否则会出现问题。 解决方法如下&…

【机器学习合集】泛化与正则化合集 ->(个人学习记录笔记)

文章目录 泛化与正则化1. 泛化(generalization)2. 正则化方法2.1 显式正则化方法显式正则化方法对比提前终止模型的训练多个模型集成Dropout技术 2.2 参数正则化方法2.3 隐式正则化方法方法对比 泛化与正则化 1. 泛化(generalization) 泛化不好可能带来的问题 模型性能不稳定容…

VNC图形化远程连接Ubuntu服务器

我的Ubuntu版本22.04.3&#xff0c;带有gnome图形桌面。配置过程参考了几篇博客&#xff0c;大致流程如下。因为是配置完之后才整理的流程&#xff0c;可能有疏漏。 Ubuntu服务器上的配置 1.先在服务器上下载vnc server&#xff08;任何一种版本均可&#xff09; vncserver有…

【管理运筹学】第 10 章 | 排队论(4,系统容量有限制和顾客源有限的情形)

文章目录 引言一、系统的容量有限制&#xff08; M / M / 1 / N / ∞ M/M/1/N/\infty M/M/1/N/∞&#xff09;二、顾客源为有限的情形&#xff08; M / M / 1 / ∞ / m M/M/1/\infty/m M/M/1/∞/m&#xff09;写在最后 引言 了解了标准的 M / M / 1 M/M/1 M/M/1 模型后&#…

【Java集合类面试二十四】、ArrayList和LinkedList有什么区别?

文章底部有个人公众号&#xff1a;热爱技术的小郑。主要分享开发知识、学习资料、毕业设计指导等。有兴趣的可以关注一下。为何分享&#xff1f; 踩过的坑没必要让别人在再踩&#xff0c;自己复盘也能加深记忆。利己利人、所谓双赢。 面试官&#xff1a;ArrayList和LinkedList有…

k8s的coreDNS添加自定义hosts

1.ack的hosts不会继承宿主机的hosts&#xff0c;而工作中有一个域名默认是走内网解析&#xff0c;内网被限制访问了&#xff0c;只能在coreDNS中加一个hosts解析域名 2.编辑configmap (coredns) kubectl edit configmap -n kube-system coredns 增加hosts节点 Corefile: |.:53…

PDF 文档处理:使用 Java 对比 PDF 找出内容差异

不论是在团队写作还是在个人工作中&#xff0c;PDF 文档往往会经过多次修订和更新。掌握 PDF 文档内容的变化对于管理文档有极大的帮助。通过对比 PDF 文档&#xff0c;用户可以快速找出文档增加、删除和修改的内容&#xff0c;更好地了解文档的演变过程&#xff0c;轻松地管理…

html 常见兼容性问题

目录 前言: 用法: 代码: 1. 盒模型差异: 2. 表格布局问题: 3. 浏览器前缀问题: 4. 字体渲染问题: 理解: 讨论: 前言: 在Web开发中&#xff0c;兼容性问题是常见的挑战之一。不同的浏览器和设备可能以不同的方式解释和呈现HTML&#xff0c;导致网页在某些环境下出现问题…

第12章 PyTorch图像分割代码框架-1

从本章开始&#xff0c;本书将会进行深度学习图像分割的实战阶段。PyTorch作为目前最为流行的一款深度学习计算框架&#xff0c;在计算机视觉和图像分割任务中已经广泛使用。本章将介绍基于PyTorch的深度学习图像分割代码框架&#xff0c;在总体框架的基础上&#xff0c;基于PA…

Fabric.js 讲解官方demo:Stickman

本文简介 戴尬猴&#xff0c;我是德育处主任 Fabric.js 官网有很多有趣的Demo&#xff0c;不仅可以帮助我们了解其功能&#xff0c;还可以为我们提供创意灵感。其中&#xff0c;Stickman是一个非常有趣的例子。 先看看效果图 从上图可以看出&#xff0c;在拖拽圆形时&#xf…

yyds,Elasticsearch Template自动化管理新索引创建

一、什么是Elasticsearch Template&#xff1f; Elasticsearch Template是一种将预定义模板应用于新索引的功能。在索引创建时&#xff0c;它可以自动为新索引应用已定义的模板。Template功能可用于定义索引的映射、设置和别名等。它是一种自动化管理索引创建的方式&#xff0…

CSDN学院 < 华为战略方法论进阶课 > 正式上线!

目录 你将收获 适用人群 课程内容 内容目录 CSDN学院 作者简介 你将收获 提升职场技能提升战略规划的能力实现多元化发展综合能力进阶 适用人群 主要适合公司中高层、创业者、产品经理、咨询顾问&#xff0c;以及致力于改变现状的学员。 课程内容 本期课程主要介绍华为…

非侵入式负荷检测与分解:电力数据挖掘新视角

电力数据挖掘 概述案例背景分析目标分析过程数据准备数据探索缺失值处理 属性构造设备数据周波数据模型训练 性能度量推荐阅读 主页传送门&#xff1a;&#x1f4c0; 传送 概述 摘要&#xff1a;本案例将根据已收集到的电力数据&#xff0c;深度挖掘各电力设备的电流、电压和功…

03.MySQL事务及存储引擎笔记

事务 查看/设置事务 select autocommit; --查看当前数据库的事务状态&#xff0c;1表示开启&#xff0c;0表示关闭 set autocommit 0; --关闭自动事务提交采用关闭自动事务提交我们就可以手动进行事务提交&#xff0c;但是这种设置方式是对整个数据库起作用&#xff0c;一些可…

MongoDB 的集群架构与设计

一、前言 MongoDB 有三种集群架构模式&#xff0c;分别为主从复制&#xff08;Master-Slaver&#xff09;、副本集&#xff08;Replica Set&#xff09;和分片&#xff08;Sharding&#xff09;模式。 Master-Slaver 是一种主从复制的模式&#xff0c;目前已经不推荐使用。Re…

互联网产品说明书指南,附撰写流程与方法

产品说明书&#xff0c;对于普通产品而言&#xff0c;再常见不过。药物、电器、电子产品等产品在正式出售时&#xff0c;往往都会附带一份产品说明书&#xff0c;以此告诉用户这个产品的功能与特性&#xff0c;并指导用户如何来使用这个产品。 产品说明书 那么&#xff0c;对于…

Python遍历删除列表元素的一个奇怪bug

假定有一个Python列表&#xff0c;比如[CFFEX.IF, CFFEX.TS,SHFE.FU]&#xff0c;现在需要将其中带‘CFFEX’前缀的所有元素都删除。在使用列表推导式一行代码搞定之前&#xff0c;用了一种最朴素的遍历删除方法&#xff0c;结果出现了意想不到的的问题。复盘了下&#xff0c;结…
最新文章