分布式架构
分布式系统是若干个,这些计算机对于用户来说就像单个相关系统,分布式是由一组通过网络进行通信,为了完成共同的任务而协调工作的计算机节点组成的系统。
RPC
RPC是指远程过程调用,是一种进程间通信方式,是一种思想而不是一种规范。它允许程序调用另一个地址空间(通常是共享网络的另一台机器上)的过程或函数,而不用程序员显式编码这个远程调用的细节。即程序员无论调用本地的还是远程的函数,本质上编写的调用代码基本相同。
RPC的两个核心:通信和序列化
Dubbo架构
Zookeeper
Zookeeper是分布式的,开放源代码的分布式应用程序协调服务,提供服务的注册与发现
安装zk
下载zk安装包,解压;
之后使用/bin/zkServer.cmd启动,启动之前编辑cmd文件,增加暂停;
在/conf文件夹下将zoo_sample.cfg文件拷贝一份,改名为zoo.cfg;
之后就能启动zk了
使用zk与dubbo
zk的简单使用
在/bin目录下启动zkCli.cmd连接本地zk服务
用
ls /命令查询节点用
create -e /lyl 479创建一个节点用
get /lyl查询
dubbo可视化监控
从github中下载dubbo-admin项目,并打包为jar包运行dubbo可视化监控,下载地址:Branches · apache/dubbo-admin · GitHub
服务端
为项目添加zk和dubbo依赖
<!-- https://mvnrepository.com/artifact/org.apache.dubbo/dubbo-spring-boot-starter -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.sgroschupf/zkclient -->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-framework -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.12.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.12.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.7.1</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>配置dubbo
dubbo:
application:
name: jetty-spring
registry:
address: zookeeper://127.0.0.1:2181
scan:
base-packages: com.example.jettyspring为dubbo服务添加注解@DubboService,这样就能注册成功了
消费者
添加与服务端同样的依赖
配置消费者配置文件
dubbo:
application:
name: test-consumer
registry:
address: zookeeper://127.0.0.1:2181消费者远程引用,引用方法有两种:使用pom坐标引用 & 定义路径相同的接口名(下面实例使用这种方式)
在消费者项目中创建相同路径的接口,一般通过方法来传递内容,不要使用自定义的类,不然会出现错误,使用String就好
public interface TestService {
String test1();
String testDubbo();
}使用@DubboReference注解,向接口注入内容
@Service
public class Consumer {
@DubboReference
TestService testService;
public String consumerTest(){
String rep = testService.testDubbo();
return rep;
}
}然后测试
@Autowired
Consumer consumer;
@Test
void contextLoads() {
String rep = consumer.consumerTest();
System.out.println(rep);
}